重读APUE(14)-主线程终止对子线程的影响

在main中创建线程,我们称main线程为主线程,新建线程为子线程(其实没有什么主线程和子线程的父子概念,它们是平行的,为了好理解这样称呼),如果子线程内部执行相对比较耗时的操作,主线程执行的快,而且没有等待子线程执行完毕,此时主线程退出,进程被销毁,就会导致子线程无法执行完毕;

可以采用如下方式确保子线程执行完毕:

1. 主线程中采用pthread_join阻塞等待子线程结束,并回收资源;

man手册对于该函数的描述:

The pthread_join() function waits for the thread specified by thread to terminate.

 

2. 主线程调用pthread_exit结束主线程;此时进程不会调用exit,而是会等待所有线程执行完毕后才执行exit;

man手册对于该问题的描述:

When a thread terminates, process-shared resources (e.g., mutexes, condition variables, semaphores, and file descriptors) are not released, and functions registered using atexit(3) are not called. After the last thread in a process terminates, the process terminates as by calling exit(3) with an exit status of zero; thus, process-shared resources are released and functions registered using atexit(3) are called.

3. 线程同步方式,主线程等待某个子线程的条件发生后,才退出;

 

需要注意的是线程分离,并不会影响退出;

线程分离,只是说线程结束会自动回收资源,不需要用pthread_join等待;当主线程退出时,子线程也一样会被销毁;

man手册对于该问题的描述:

The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if
the process terminates using exit(3) (or equivalently, if the main thread returns).

本文链接:重读APUE(14)-主线程终止对子线程的影响

转载声明:转载请注明来源:Linux TCP/IP Stack,谢谢!


发表评论

电子邮件地址不会被公开。 必填项已用*标注