【问题标题】:what happen if the main thread finish but peer threads are not?如果主线程完成但对等线程没有完成怎么办?
【发布时间】:2020-10-21 09:41:29
【问题描述】:

我是 C 和多线程编程的新手,只是一个关于如果主线程完成但对等线程没有完成会发生什么的问题,进程是否仍等待所有对等线程完成或进程在主线程后立即终止完成了吗?

【问题讨论】:

  • 考虑阅读有关pthread_join 和相关功能的文档。

标签: c multithreading


【解决方案1】:

main函数返回,或者你调用exit时,系统将终止该进程以及该进程中运行的所有线程。

如果您有想要继续运行的后台(分离)线程,您必须只结束“主”线程,而不是进程。如何做到这一点取决于平台,但在 POSIX 平台(例如 Linux 或 macOS)上,您调用 pthread_exit 而不是 exit

如果你没有任何后台线程,那么你需要加入所有正在运行的线程,以防止它们被强制终止。

【讨论】:

    【解决方案2】:

    这是一个示例程序,它说明了 GLIBC/Linux 操作系统上的上述答案。程序创建一个分离的辅助线程,如果没有传递参数,则主线程退出,否则调用pthread_exit():

    #include <pthread.h>
    #include <stdio.h>
    #include <errno.h>
    #include <unistd.h>
    
    
    void *th_entry(void *p)
    {
      int i;
    
      printf("Secondary thread starting...\n");
    
      for (i = 0; i < 5; i ++) {
        printf(".");
        fflush(stdout);
        sleep(1);
      }
    
      printf("\nSecondary thread exiting\n");
    
      return NULL;
    }
    
    
    int main(int ac, char *av[])
    {
      int rc;
      pthread_t tid;
    
      printf("Main thread starting...\n");
    
      rc = pthread_create(&tid, NULL, th_entry, NULL);
      if (rc != 0) {
        errno = rc;
        fprintf(stderr, "pthread_create(): '%m' (%d)\n", errno);
        return 1;
      }
    
      // Detach the secondary thread
      rc = pthread_detach(tid);
      if (rc != 0) {
        errno = rc;
        fprintf(stderr, "pthread_detach(): '%m' (%d)\n", errno);
        return 1;
      }
    
      // Some dummy work
      sleep(1);
    
      if (av[1]) {
        printf("Main thread exiting\n");
        return 0;
      } else {
        printf("Main thread calling pthread_exit()\n");
        pthread_exit(NULL);
      }
    
      return 0;
    
    }
    

    编译:

    $ gcc td.c -l pthread
    

    当程序没有传递任何参数时,主线程调用pthread_exit(),当次线程结束时进程结束。

    $ ./a.out
    Main thread starting...
    Secondary thread starting...
    .Main thread calling pthread_exit()
    ....
    Secondary thread exiting
    $
    

    当程序传入参数后,主线程调用exit()(返回0但等价),进程立即结束,终止从线程:

    $ ./a.out 1
    Main thread starting...
    Secondary thread starting...
    .Main thread exiting
    $
    

    【讨论】:

      猜你喜欢
      • 2011-06-05
      • 2014-10-05
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多