- 主线程和子线程之间没有必然的退出次序关系。主线程退出,子线程可以继续执行;子线程退出,主线程也可以继续执行。
- 程序加载到内存中执行的时候,进程就会生成一个主线程。虽然主线程和子线程之间没有必然的退出次序关系,但是如果进程终止,那么进程下所有的线程都会终止。
子线程先终止,主线程后终止
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void printids(const char *str) {
pid_t pid = getpid();
pthread_t tid = pthread_self();
printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *func(void *arg) {
printids("descendant thread");
pthread_detach(pthread_self());
return ((void*)0);
}
int main(void) {
pthread_t myid;
pthread_create(&myid, NULL, func, NULL);
sleep(1); // 等待子线程先退出
printids("main thread");
return 0;
}
进程结束,所有线程都终止
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void printids(const char *str) {
pid_t pid = getpid();
pthread_t tid = pthread_self();
printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *func(void *arg) {
sleep(1); // 等待主线程先退出
printids("descendant thread");
pthread_detach(pthread_self());
return ((void*)0);
}
int main(void) {
pthread_t myid;
pthread_create(&myid, NULL, func, NULL);
// sleep(1); // 等待子线程先退出
printids("main thread");
return 0; //进程退出,系统清除所有资源
}
进程结束,子线程部分来不及执行
主线程先终止,子线程后终止
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void printids(const char *str) {
pid_t pid = getpid();
pthread_t tid = pthread_self();
printf("%s pid: %u, tid: %u, tid in 0x presentation: 0x%x.\n",str, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
}
void *func(void *arg) {
sleep(1); // 等待主线程先退出
printids("descendant thread");
pthread_detach(pthread_self());
return ((void*)0);
}
int main(void) {
pthread_t myid;
pthread_create(&myid, NULL, func, NULL);
printids("main thread");
pthread_exit(NULL);
return 0; //进程退出,系统清除所有资源
}
当主线程在子线程终止之前调用pthread_exit()时,子线程是不会退出的。
注意:这里在main函数中调用pthread_exit()只会是主线程退出,而进程并未退出。参照CSAPP中的讲解,当主线程执行pthread_exit()之后,主线程终止,进程并未终止,而是等待所有的子线程终止之后再结束。