线程取消
一个线程可以对另一个线程提出取消申请,即线程被动终止的一种情况。向某个线程提出取消申请的接口:
#include <pthread.h>
int pthread_cancel(pthread_t thread);
如果一个线程因响应pthread_cancel而终止的,那么连接该线程时,将得到PTHREAD_CANCELED返回值。
向线程提出取消申请,与线程真正发生终止之间,是异步的。即向线程发出取消申请,被申请线程不一定会马上终止,而是等到某个可以发生终止的时机了才终止。可以发生终止的时机,是指当线程调用某些函数时,会响应取消请求,这些函数也称为线程的取消点。 常见的线程取消点有:
实例:
/* *thread_cancel.c */ #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<errno.h> #define handle_error_en(en, msg) \ do {errno = en; perror(msg); exit(EXIT_FAILURE) ;} while(0) static void *thread_routine(void *arg) { int j; printf("New thread started\n"); //这里又可能是一个线程取消点 for (j = 1; ; j++) { printf("Loop %d\n", j); //这里也可能是一个线程取消点 sleep(1); //这里也可能是一个线程取消点 } //程序执行流程时无法到达这里 return NULL; } int main() { pthread_t thr; int s; void *res; s = pthread_create(&thr, NULL, thread_routine, NULL); if (0 != s) { handle_error_en(s, "pthread_create"); } sleep(3); s = pthread_cancel(thr); if (0 != s) { handle_error_en(s, "pthread_cancel"); } //等待线程退出 s = pthread_join(thr, &res); if (0 != s) { handle_error_en(s, "pthread_join"); } //判断新线程终止是否是相应取消而终止的 if (res == PTHREAD_CANCELED) { printf("Thread was canceled\n"); } else { printf("Thread was not canceled (should not happen!)\nA;"); } return 0; }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)