【问题标题】:Multithreading concepts: would `threading` execute the return statement before all the child threads finish executing?多线程概念:`threading` 会在所有子线程完成执行之前执行 return 语句吗?
【发布时间】:2016-09-08 04:52:02
【问题描述】:

我有一个最近困扰我的线程问题。看看下面这个示例 C# 代码。

 public void threading()
 {
     for(int count =0; count< 4; count++)
     {
        Thread childThread = new Thread(childThread);
        childThread.start()
     }

     return;
 }

public void childThread()
{
 // Do alot of work 
}

由于threading 方法中的循环之后有一个return 语句,threading 会在所有子线程完成执行之前执行return 语句吗?我在某处读到线程与分叉不同,因为它们不会创建单独的内存区域,那么死线程最终会在哪里?

【问题讨论】:

  • C# Thread object lifetime的可能重复
  • "threading 会在所有子线程完成执行之前执行 return 语句吗?" - 是的,因为它在单独的线程中运行。
  • “死线”是什么意思?
  • 这是一劳永逸的代码。很少正确,您不知道线程何时完成并且很少希望正确处理错误。它让你问了这个问题。请考虑 Task 类。

标签: c# multithreading


【解决方案1】:

线程是否会在所有子节点之前执行 return 语句 线程完成执行了吗?

也许是的。也许不会。这完全取决于您的 childThread 方法执行需要多长时间。如果您的 childThread 方法花费的时间确实更少,那么可能会发生所有四个线程在threading 方法中执行 return 语句之前完成。

另一方面,如果需要很长时间,那么即使在 threading 方法完成执行或返回到 Main 之后,您的线程也可以继续异步执行。

您需要了解的另外一件事:

默认情况下,他们创建的所有这些线程都是后台线程。因此,只要您的流程存在,它们就会存在。如果您的主 GUI 线程将要结束,那么这四个线程也将被折腾并被中止。因此,您的四个线程必须至少有一个前台线程处于活动状态才能继续执行childThread 方法才能运行完成。

就内存而言 - 创建的每个线程都有自己的堆栈内存区域,但它们共享公共堆内存。此外,无论是线程的堆栈内存还是堆内存,它肯定会位于进程自身地址空间的外围。

【讨论】:

    【解决方案2】:

    如果您想强制所有子线程在您的threading 方法返回之前终止,您可以在线程上使用Join 方法,例如

    public void Threading()
    {
        List<Thread> threads = new List<Thread>();
    
        // start all threads
        for(int count =0; count< 4; count++)
        {
            Thread childThread = new Thread(ChildThread);
            childThread.start();
            threads.Add(thread);
        }
    
        // block until all threads have terminated
        for(int count =0; count< 4; count++)
        {
            threads[count].Join();
        }
    
        // won't return until all threads have terminated
        return;
    }
    
    public void ChildThread()
    {
        // Do alot of work 
    }
    

    【讨论】:

    • 太棒了。它如何解决“线程会在所有子线程完成执行之前执行return语句吗?”? :)
    • 我很感激这并不能回答字面上的问题。 “X会做Y吗?”的另一种解释问题是“我怎样才能让 X 做 Y?”,这就是答案(“我怎样才能让方法只在所有子线程完成执行后才返回?”)。
    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多