方式一、孙线程在son线程中阻塞回收
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
pthread_t pid_1,pid_2;
void *func2(void *arg)
{
while(1)
{
printf("this is grandson\n");
sleep(1);
}
}
void *func1(void *arg)
{
pthread_create(&pid_2,NULL,func2,NULL);
printf("this is son\n");
sleep(10);
pthread_join(pid_2,NULL);
printf("func1--son exit \n");
}
int main(int argc, char *argv[])
{
pthread_create(&pid_1,NULL,func1,NULL);
pthread_join(pid_1,NULL);
printf("main--son exit \n");
// pthread_join(pid_2,NULL);
printf("father exit\n");
return 0;
}
方式二:孙线程在主线程中阻塞回收
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
pthread_t pid_1,pid_2;
void *func2(void *arg)
{
while(1)
{
printf("this is grandson\n");
sleep(1);
}
}
void *func1(void *arg)
{
pthread_create(&pid_2,NULL,func2,NULL);
printf("this is son\n");
sleep(10);
// pthread_join(pid_2,NULL);
printf("func1--son exit \n");
}
int main(int argc, char *argv[])
{
pthread_create(&pid_1,NULL,func1,NULL);
pthread_join(pid_1,NULL);
printf("main--son exit \n");
pthread_join(pid_2,NULL);
printf("father exit\n");
return 0;
}
小结:我们看到,son线程的退出,并没有影响到孙线程的运行,因为进程并未退出。
查看线程的方法:参考该文
以上述方式一的形式查看线程:
总结:
1)同一进程中的线程是平等的,没有父子之分。当然也包括所谓的主线程、在主线程中创建的线程、在所谓的子线程中创建的线程。
线程既然是平等的,只要进程不退出,倘若son线程退出,我们看到不会影响到孙线程的运行。
2)孙线程在子线程中创建,可以理解为,启动孙线程的顺序点是在此时,而并非在主线程中。
也就是说,我们可以在任意我们需要创建一个平行任务的地方,创建一个子线程,而并非得在主线程中创建。
3)线程函数,其实,就可以理解为就是一个函数(当然单独调用也能用),与普通函数不同的是,线程函数能够与其他函数并行(同时执行,而非线程函数只能顺序执行。)