atomic - Reproduce torn reads of decimal in c# -
Seeing is believing can someone reproduce a program that read broken decimal? I tried spinning multiple threads between 1 and 2 changing the same decimal. I could not read any one from 1 or 2
Edit: I have to see that a reader thread does not appear atomic, with a writer thread, so the value should be somewhat different from 1 or 2.
Turn-throughcillight test by zero ({decimal share = decimal = 1; Int threadCount = 100; Var thread = new list & lt; Thread & gt; (); {Int threadId = i; for int i = 0; i & lt; threadcount; i ++) Var thread = new thread ((=) gt; {thread.sleep (5000); decimal newvalue = thread id% 2 == 0? 1: 2; bool; thread thread = thread ID% 2 == 0; console "Light" ("Author:" + isWriterThread + "- will set the value" + newValue ", for (int j = 0; j and lt; 1000000; j ++) {if (isWriterThread) sharedDecimal = newValue; decimal decimal = Shared Decimals; if (decimal read! = 1 & amp; & amp; nbsp; decimal red! = 2) console; light line (decimal read);}}) threads.Add (thread);} threads. x = & gt; x.start ()) threads. foeric (x = & gt; x.joint ());}
This code will display a torn read of a decimal : Using the system, using the system; Threading Task; Namespace Console App1 {Class Program {zero} (Task.ron (action) setter); Task.Run (Action Checker); Console.ReadLine ();} zero setter (while {true} {d = VALUE1; D = VALUE2;}} zero checker (); console (light) ("press to stop press" {For (int count = 0 ;; ++ count) {var t = d; If (T! = VALUE1 & amp; t! = VALUE2) console Type ("value has exploded after {0} iterations: {1}", count, t); }} Static zero major () {new program (). Run (); } Decimal d; Fixed decimal VALUE1 = 1 m; Const decimal 1, 2, 2, 10000000000 m; }} This is faster than the debugging build in the release build.
I think you are not seeing tearing your test code because you were only changing the value between 0 and 1. It is possible that during your testing the bits are being changed, all are used to store the value internally in the same word, and the use of words is atomic.
By changing the value between 1 and 10000000000, we force the bits to be converted into two different words, which allow for tearing.
Comments
Post a Comment