locking - C# waiting for an counter value fails -
i've got fragment of code uses callback modify counter value other thread. i'm using lock , empty while loop checking if counter == 0. works when running in visual studio. however, after "releasing" , running binary freezes. while loop presented below, callback method body.
what may causing it?
thanks,
public void somemethod() { //starting bunch of threads calling callback method while(counter > 0) {} } public void callback() { lock (this) { countdown--; } }
locks needed every time access variable shared between threads, not in 1 location. in case code in while
loop not introducing memory barrier when accessing counter
, such jitter allowed create optimizations such reading cached version of value, or noticing value can't have been written , avoiding repeating read ever.
in specific case utilize volatile.read(ref counter)
, work, should very wary of trying utilize lock-free or low-lock programming, or using these low level synchronization primitives. should strive instead utilize higher level synchronization primitives. in specific case semaphore
appropriate. initialize inverse of countdown value, release in callback, , wait in method.
locking on implicit parameter (this
) code smell. should strive ever lock on objects in small, rigidly controlled, scope, avoid deadlocks result of locks beingness taken out on object wide scope of code base.
c# locking
No comments:
Post a Comment