【问题标题】:confusion regarding Thread.Join关于 Thread.Join 的困惑
【发布时间】:2016-01-20 07:40:47
【问题描述】:

我对@9​​87654322@ 方法有点困惑。我看过 THIS MSDN 帖子和一些 SO 帖子,但无法消除这种混乱。

如果有多个线程,是否等待所有线程完成?还是阻塞下一个线程的执行,直到第一个线程完成?假设以下场景:

List<Thread> myThreads = new List<Threads>();
while(someCondition == true)
{
   Thread thread = new Thread(new ThreadStart(delegate 
                {
                    processSomeCalculations(x, y);
                })); 
    thread.Start();
    myThreads.Add(thread);

}

foreach (Thread thread in myThreads)
{
   thread.Join();
}

Print("all threads completed now");

在上述场景中,当thread.Join() 被调用为列表的第一项(即列表的第一个线程)时,does it mean that thread 2 (i.e, the second thread of the list) can NEVER continue its execution, until first thread has been completed?

这是否意味着,all the threads in the list will continue execution in PARALLEL manner, and PRINT method will be called after all threads have finished execution?

我的问题总结: 在上述情况下,所有线程都会继续并行执行吗?或者他们会在第一个执行完之后一个一个执行?

【问题讨论】:

  • 你为什么不写代码来测试一下?

标签: c# multithreading concurrency parallel-processing


【解决方案1】:

是后者,它只会阻塞主线程上的执行,直到你生成的所有线程都完成执行,或者在本例中以processSomeCalculations(x, y) 完成,然后打印"all threads completed now"

【讨论】:

    【解决方案2】:

    正如雅各布已经说过的,是后者。 另外,你可以把你的代码想象成这样:

    1.) 启动多个线程

    2.) 然后在你的循环中:从列表中取出第一个线程并阻塞主线程,直到第一个线程完成。只有主线程(即调用.Join() 的线程)被阻塞,所有其他线程继续。

    3 ... n.) 再次在循环内:获取下一个线程并阻塞主线程,直到这个线程完成(或者如果线程已经完成则继续)

    循环结束后,您可以确定所有线程都已完成。

    【讨论】:

    • 所以这意味着,在我的情况下,如果我在循环内 thread.start() 之后立即调用 thread.Join (而不是像我在 while 循环之后所做的 foreach 循环),它将具有效果一样吗?
    • 不,在这种情况下你会 1. 启动第一个线程 2. 等到第一个线程完成 3. 启动第二个线程 4. 等到第二个线程完成 5. ...调用myThread.Join() 的线程被阻塞,直到myThread 完成。
    猜你喜欢
    • 2019-05-17
    • 2020-03-06
    • 2016-03-16
    • 2013-07-27
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多