Can someone explain me this:
if inserting Thread.Yield() anywhere in your code makes or breaks the program, you almost certainly have a bug.
I've read it here : http://www.albahari.com/threading/
Can someone explain me this:
if inserting Thread.Yield() anywhere in your code makes or breaks the program, you almost certainly have a bug.
I've read it here : http://www.albahari.com/threading/
I can only guess to the author's intent, but: thread scheduling is already indeterminate. If adding the yield makes it work, then I infer that the reality here is that it is relying on the side-effect of a race condition, i.e. giving some CPU to another thread allows the timings to coincide such that the right thing happens. Well, you don't know what you are yielding to on a parallel system, and on a milticore system you may well not be yielding to the same thing (yield is same CPU only). As such, the only sane way to do this is with a structure such as a Monitor, Mutex, Semaphore, ResetEvent, or some other locking primitive designed for allowing controlled flow between threads and (sometimes) processes.
My assumption, which I have discussed here, is that Thread.Yield
generates an implicit memory barrier. If you had a memory barrier issue it could disappear by adding a call to Thread.Yield
. This is similar to how using Thread.Sleep
to simulate thread interleaving can actually wind up masking a problem. Also, Thread.Yield
will obviously change the timing of when instructions get executed and that can have an impact on whether or not a race condition is observed or not.