pthread_setcancelstate 函数是 POSIX 线程(pthread)库中的一个函数,用于设置线程的取消状态。在 POSIX 线程中,线程可以被其他线程或自身请求取消,但线程可以决定自己是否对取消请求敏感。这就是通过 pthread_setcancelstate 函数来控制的。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void* thread_function(void* arg)
{
int oldstate;
// 禁用取消
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
// 执行一些不能被取消的操作
// ...
printf("我在执行一个很重要的事情,不能取消我\n");
sleep(5);
printf("重要的事情-执行完毕\n");
// 恢复取消状态
pthread_setcancelstate(oldstate, NULL);
printf("可以取消\n");
// 现在线程可以被取消了
// ...
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread; // 线程 ID
pthread_create(&thread, NULL, thread_function, NULL); // 创建线程
// 假设在某个点,我们决定取消线程 (主线程)
while (1)
{
printf("请输入要执行的动作\n");
printf("1、正常运行\n");
printf("2、取消线程\n");
int num = 0;
scanf("%d", &num);
while(getchar()!= '\n'); // 清空输入缓冲区
switch (num)
{
case 1:
printf("正常运行中......\n");
break;
case 2:
pthread_cancel(thread); // 取消线程
break;
}
}
pthread_join(thread, NULL); // 等待线程结束
return 0;
}