简体   繁体   English

如果主线程完成但对等线程没有完成会发生什么?

[英]what happen if the main thread finish but peer threads are not?

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

When the main function returns, or you call exit , then the system will terminate the process and all threads running in that process.main函数返回时,或者您调用exit ,系统将终止该进程以及该进程中运行的所有线程。

If you have background (detached) threads that you want to keep running, you have to end the "main" thread only, not the process.如果您有要继续运行的后台(分离)线程,则必须仅结束“主”线程,而不是进程。 How to do that is platform-dependent, but on POSIX platforms (eg Linux or macOS) then you call pthread_exit instead of exit .如何做到这一点取决于平台,但在 POSIX 平台(例如 Linux 或 macOS)上,您可以调用pthread_exit而不是exit

If you don't have any background threads then you need to join all the running threads to keep them from being forcibly terminated.如果您没有任何后台线程,那么您需要加入所有正在运行的线程以防止它们被强行终止。

Here is an example program which illustrates the preceding answer on GLIBC/Linux operating system.这是一个示例程序,它说明了 GLIBC/Linux 操作系统上的上述答案。 The program creates a detached secondary thread and if it is not passed a parameter, the main thread exits otherwise it calls pthread_exit():程序创建一个分离的辅助线程,如果没有传递参数,主线程退出,否则调用 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;

}

Compile it:编译它:

$ gcc td.c -l pthread

When the program is not passed any parameter, the main thread calls pthread_exit() and the process ends when the secondary thread finishes.当程序没有传递任何参数时,主线程调用 pthread_exit() 并且当辅助线程完成时进程结束。

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

When the program is passed a parameter, the main thread calls exit() (it returns 0 but it is equivalent) and the process ends immediately terminating the secondary thread:当程序被传递一个参数时,主线程调用exit()(它返回0但它是等效的)并且进程立即结束并终止辅助线程:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM