开发者

Starting threads and waiting for them all to finish

开发者 https://www.devze.com 2023-04-03 05:22 出处:网络
I have the following piece of code (C#): is it correct? Thread[] threads = new Thread[totalThread]; for (int i=0; i<totalThread; i++) {

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.

0

精彩评论

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

关注公众号