2

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/

Liran
  • 1,596
  • 1
  • 13
  • 11
Erez
  • 6,405
  • 14
  • 70
  • 124
  • Please don't start your titles with things like "C#" - that's what tags are for. Even more so, this question has nothing to do with C# - it's a pure .NET question. – John Saunders Aug 06 '11 at 21:44
  • 1
    That's wishful thinking. Could work, but just not very likely. Flushing out threading race bugs requires a bigger weapon. A good gun is Microsoft Lab's CHESS tool, it injects random delays into threads. http://research.microsoft.com/en-us/projects/chess/ – Hans Passant Aug 06 '11 at 21:56
  • @Hans: afair, chess does not only injects random delays, it is capable of analyzing control flow of the program and model different execution scenarios. – Ivan Danilov Aug 07 '11 at 05:47

2 Answers2

5

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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.

Community
  • 1
  • 1
Brian Gideon
  • 47,849
  • 13
  • 107
  • 150