开发者

Calling thread.sleep() while waiting for a new thread to spawn

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开发者_如何学Python suggest spinning because it's slightly more elegant and the time difference is negligible?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜