Tim Barrass
Tim Barrass

Reputation: 4939

Timing of thread transition from Unstarted to Running

"An Unstarted thread is transitioned into the Running state by calling Start." [from msdn ThreadState enumeration docs.

Exactly when does a thread transition from Unstarted to Running?

If I instantiate a thread and call Start, is there a delay before the thread actually moves to Running? If the instantiating thread calls Join immediately after Start, is there a risk it'll catch the new thread in an Unstarted state?

Upvotes: 2

Views: 378

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113382

  1. Its state becomes Running before the Start() method returns, though it may not yet (and quite often will not) have done any actual work, as it may not yet have been given any core time. Most of the time the fact that we can think of the tread as running is enough (just as most of the time we can think "we have 6 threads running" when if we only have 4 cores the obviously we've only got up to 4 actually doing something). It could also be that by the time you get to the next instruction on the calling thread, that it's WaitSleepJoin or even Stopped but it won't be Unstarted.

  2. It's perfectly safe to call Join() even in the very next statement after Start() (though that would rarely be useful).

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

The documentation for ThreadState.Unstarted states

Unstarted   The Thread::Start method has not been invoked on the thread.

In other words, no, you can't end up with Thread.Unstarted after Thread::Start has been called. The Thread is not guaranteed to be in ThreadState.Running though, it could be in for example ThreadState.WaitSleepJoin if it blocks on a Mutex before you check the state.

The only ThreadState that causes problems with Join is ThreadState.Unstarted though, so calling Join is safe right after Start, provided Start does not throw an exception.

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64537

The call to Start isn't asynchronous, so the method would return with the thread started. I've done this in a few sample apps and calling Join immediately afterwards never caused any problems.

Upvotes: 1

Related Questions