简体   繁体   中英

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 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.

这篇文章解释了SpinWait的使用,并提到了不同类型的睡眠http://www.emadomara.com/2011/08/spinwait-and-lock-free-code.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM