#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
void cleanup_handler(void *arg) {
printf("Cleanup handler is called with argument: %s\n", (char *)arg);
// 执行清理工作
}
void *threadFunction(void *arg) {
// 设置线程的取消状态为可取消
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
// 设置线程的取消类型为推迟取消(这样清理函数才有机会被执行)
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
// 注册清理函数
pthread_cleanup_push(cleanup_handler, "cleanup argument");
printf("Thread started, entering loop.\n");
while (1) {
// 创建取消点
printf("runing...1\n");
pthread_testcancel();
printf("runing...2\n");
printf("runing...3\n");
// 执行一些工作...
sleep(1); // 模拟耗时操作
printf("runing...4\n");
}
// 弹出清理函数(不会被执行,除非线程被取消)
pthread_cleanup_pop(0);
}
void signal_handler1(int signum)
{
printf("signal_handler() in 1\n");
}
void signal_handler2(int signum)
{
printf("signal_handler() in 2\n");
}
int main() {
pthread_t thread;
signal(34, signal_handler1);
signal(35, signal_handler2);
sleep(20);
sleep(20);
// 创建线程
if (pthread_create(&thread, NULL, threadFunction, NULL) != 0) {
perror("Failed to create thread");
return 1;
}
// 模拟主线程的其他工作
sleep(3);
// 请求取消线程
printf("Requesting thread cancellation.\n");
if (pthread_cancel(thread) != 0) {
perror("Failed to cancel thread");
return 1;
}
// 等待线程结束
pthread_join(thread, NULL);
printf("Main thread finished.\n");
return 0;
}
注意:pop和push 必须在一个条件语句中,不能分开。