可以通过以下三种方式在不终止进程的情况下退出线程
1 线程从执行函数中返回
2 线程调用pthread_exit 函数退出
3 线程可以被同一进程的其它线程取消
#include<pthread.h>
void pthread_exit(void *retval);
/*
功能 退出线程,一个进程中的多个线程是共享该进程中的数据段,因此,通常线程退出后所占用的资源并
不会释放
参数 retval 存储线程退出状态的指针
返回 无
*/
// pthread_exit1.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
void *func1(void *arg){
int i=0;
for(i=0;i<5;i++){
printf("func1 %d\n",i);
sleep(1);
}
//这两句都是退出线程,这样写是等价的
pthread_exit(NULL);
//return NULL;
// 这句会退出整个程序
//exit(0);
}
int main(){
int ret=-1;
pthread_t tid=-1;
pthread_create(&tid,NULL,func1,NULL);
printf("press any key quit\n");
getchar();
return 0;
}
// 编译 gcc pthread_exit1.c -pthread -o pthread_exit1
// 运行 .pthread_exit1 不贴图了
//
线程取消
#include<pthread.h>
int pthread_cancel(pthread_t thread);
/*
功能 杀死(取消)线程
参数 thread 目标线程ID
返回 成功 0 失败 -1
线程取消并不是实时的,而是有一定延时,需要等待线程达到某个取消点,类似于游戏中的存档,必须到达某个
指定场所(仓库,城里 等)才能存储进度,杀死线程也不是立刻就能完成,必须要达到取消点。
取消点 是线程检查是否被取消,并按请求进行动作的一个位置,通常是一些系统调用 如 create,open,pause
等,(man 7 pthreads 可查看全部) 可粗略的认为一个系统调用(进入内核)即为一个取消点.
*/
// pthread_cancel.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
void *func1(void *arg){
int i=0;
for(i=0;i<5;i++){
printf("func1 %d\n",i);
sleep(1);
}
pthread_exit(NULL);
}
int main(){
int ret=-1;
pthread_t tid=-1;
pthread_create(&tid,NULL,func1,NULL);
sleep(3);
printf("sleep 3s cancel\n");
pthread_cancel(tid);
return 0;
}
// 编译 gcc pthread_cancel.c -pthread -o pthread_cancel
// 运行 ./pthread_cancel 结果如下
//
发布于 2021-01-15 21:24