c# - Race condition in program -
i new threading. so, created 4 dedicated threads (rather using tasks) 1 after other, , giving them work. but, made me doubt race condition in startprocessing function storing value on currentindex local variable within lock. however, ran many times, not satisfy there no race issue or else.
please me clear thing.
class program { private static object synclock = new object(); int num = 0; int currentindex = 0; static void main(string[] args) { program p = new program(); p.num = 1000; p.callthreadcreation(); while (p.num > 0) { thread.sleep(1000); } console.writeline("all done"); } public void callthreadcreation() { (int = 1; <= 4; i++) { string name = "t" + i; thread t = new thread(new threadstart(() => startprocessing())); t.name = name; t.start(); } } **private void startprocessing() { while (num > 0) { int tempindex; lock (synclock) { tempindex = currentindex; } interlocked.decrement(ref num); interlocked.increment(ref currentindex); print(tempindex); thread.sleep(1000); } }** private void print(int x) { console.writeline(x); } }
consider startprocessing
method. imagine 4 threads arrive @ while
check together. since loop check isn't synchronized, 4 might enter loop when num
is, say, 2.
- first thread arrives @
while
check. sees num > 0. enters loop. releases context. - second thread arrives @
while
check. num still 2, > 0. - repeat third , fourth threads.
- now you're in race condition. 4 threads inside loop body , unprotected
while
check. decrement operations nicely atomic , synchronized, you'll still @ -2 when 4 operations complete. have > 0 test, it's performed outside lock. thus,currentindex
might incremented more 1000 times - as 1003 times, think, 1 increment each thread might have entered loop unnecessarily.
Comments
Post a Comment