linux下pthread_cancel无法取消线程的原因
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
·
一个线程可以调用pthread_cancel终止同一进程中的另一个线程,但是值得强调的是:同一进程的线程间,pthread_cancel向另一线程发终止信号。系统并不会马上关闭被取消线程,只有在被取消线程下次系统调用时,才会真正结束线程。或调用pthread_testcancel,让内核去检测是否需要取消当前线程。被取消的线程,退出值,定义在Linux的pthread库中常数PTHREAD_CANCELED的值是-1。
#include <pthread.h>
int pthread_cancel(pthread_t thread);
看下面程序:
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
void *thread_fun(void *arg)
{
int i=1;
printf("thread start \n");
while(1)
{
i++;
}
return (void *)0;
}
int main()
{
void *ret=NULL;
int iret=0;
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
sleep(1);
pthread_cancel(tid);//取消线程
pthread_join(tid, &ret);
printf("thread 3 exit code %d\n", (int)ret);
return 0;
}
会发现程序再一直运行,线程无法被取消,究其原因pthread_cancel向另一线程发终止信号。系统并不会马上关闭被取消线程,只有在被取消线程下次系统调用时,才会真正结束线程。如果线程里面没有执行系统调用,可以使用pthread_testcancel解决。
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
void *thread_fun(void *arg)
{
int i=1;
printf("thread start \n");
while(1)
{
i++;
pthread_testcancel();
}
return (void *)0;
}
int main()
{
void *ret=NULL;
int iret=0;
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
sleep(1);
pthread_cancel(tid);//取消线程
pthread_join(tid, &ret);
printf("thread 3 exit code %d\n", (int)ret);
return 0;
}
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 5 年前
5def40a3
Add host customization support for the NodeJS version 5 年前
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐


所有评论(0)