3

I suppose this question can be boiled down to "SpinWait vs. Block?", but I figured there may be a more interesting answer as to why nearly every C# threading tutorial suggests the following call:

Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.Start()
while (!newThread.isAlive()) ;
Thread.Sleep(1); // Allow the new thread to do some work

As opposed to blocking like so:

Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.Start()
while (!newThread.isAlive()) Thread.Sleep(1);
Thread.Sleep(1); // Allow the new thread to do some work

My very brute-force testing (surrounding the while loop with calls to DateTime.Ticks) doesn't really reveal anything (says the difference is 0 ticks in both instances).

Is the thread creation process short enough that spinning is more efficient? Or do most tutorials suggest spinning because it's slightly more elegant and the time difference is negligible?

Dariusz Woźniak
  • 9,640
  • 6
  • 60
  • 73
wger
  • 31
  • 2

3 Answers3

2

I don't know why you'd use either- off the top of my head, I can't think of any use case for blocking the calling thread until the new thread is alive, since being "Alive" doesn't mean that it has executed anything. If you need to wait for some code to have been run in the new thread before proceeding on the calling thread, you'd want to use a WaitHandle or SpinLock.

Chris Shain
  • 50,833
  • 6
  • 93
  • 125
  • This might be required if the new thread needs to allocate some resource/s before it can be safely used. Some resources, (eg. a Windows message queue), are bound to the thread that creates them and so cannot be allocated in a ctor - they have to be allocated by the new thread. If the ctor does not wait for the new thread to allocate such resources, there is the possibility that the thread might be asked to perform an action that wil fail because it hasn't got round to allocating the resources yet. Passing an event to the thread, as suggested by Dani, is OK. – Martin James Jun 16 '11 at 08:20
1

You can make the thread set an event when it starts and the main thread to wait on the event. no spinwait no too long sleeping.

Daniel
  • 30,896
  • 18
  • 85
  • 139
0

This an article explains the use of SpinWait and also mentions different types of Sleep http://www.emadomara.com/2011/08/spinwait-and-lock-free-code.html

Emad Omara
  • 512
  • 4
  • 3