Starting threads and waiting for them all to finish
I have the following piece of code (C#): is it correct?
Thread[] threads = new Thread[totalThread];
for (int i=0; i<totalThread; i++) {
threads[i] = new Thread(new ThreadStart(Work));
}
sw.Start();
for (int j=0; j<num_threads; j++) {
threads[j]开发者_运维知识库.Start();
}
for (int k=0; k<num_threads; k++) {
threads[k].Join();
}
sw.Stop();
sw
is a Stopwatch, work
is some method. I would like to time this method, using a few threads, but the whole thing freezes (seems like it is not joining). I need to know if my thread handling is good, or if I'm screwing up. If the latter, it is obvious that my problem lies in the method I'm calling, rather than in thread mgmt. Thanks.
Since you mentioned freezing. Try to review your Work method and look for deadlocks. Also, add some timeout mechanism on your Join calls.
It's perfect as it is. I don't see any problem other that the num_threads
/totalThread
. Note that if totalThread
is big (where with big I mean bigger than 1-2 for each CPU Core), you should probably use the ThreadPool
.
You could get rid of the .Join loop and use a ManualResetEvent in each thread.
You would then wait on the ManualResetEvents to all become signaled.
精彩评论