thread join question

E

Eps

I understand that if I want to wait for a thread to stop then I can use
the join menthod.

If I have more than one thread, and I want to wait until they have all
stopped, what is the best way of doing this ?.



Thread1.Join();
Thread2.Join();
Thread3.Join();
Thread4.Join();

If I do the above are there any performance issues depending on whether
certain threads take longer than others ?.

Any help appreciated.
 
B

Barry Kelly

Eps said:
I understand that if I want to wait for a thread to stop then I can use
the join menthod.

If I have more than one thread, and I want to wait until they have all
stopped, what is the best way of doing this ?.

Thread1.Join();
Thread2.Join();
Thread3.Join();
Thread4.Join();

If I do the above are there any performance issues depending on whether
certain threads take longer than others ?.

Depending on the ordering of the threads finishing, the thread doing the
joining may be woken a number of times only to go back to sleep again. I
personally wouldn't worry about it, but another (more complex => more
buggy potentially) way to handle it would be to keep an active thread
count (protected by a lock or using interlocked operations), decrement
it by one on each thread ending, and when it reaches zero set an event
(a ManualResetEvent). Have the joining thread wait on that event.

-- Barry
 
J

Jon Skeet [C# MVP]

Barry Kelly said:
Depending on the ordering of the threads finishing, the thread doing the
joining may be woken a number of times only to go back to sleep again.

<snip>

If you have to wait on enough threads that that would be an issue,
you're almost certainly using too many threads to start with! I doubt
that it would ever be a significant performance hit.
 
E

Eps

Jon said:
<snip>

If you have to wait on enough threads that that would be an issue,
you're almost certainly using too many threads to start with! I doubt
that it would ever be a significant performance hit.

Cool, thanks for your help people.
 
B

Barry Kelly

Jon said:
<snip>

If you have to wait on enough threads that that would be an issue,
you're almost certainly using too many threads to start with! I doubt
that it would ever be a significant performance hit.

I agree, I don't think I'd ever do it the other way either.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top