/*
#include <pthread.h>
int pthread_cancel(pthread_t thread)
功能:取消线程(让线程终止)要到某个取消点才会取消
取消某个线程,可以终止某个线程的运行,
但不是立马终止,而是当子线程执行到一个取消点,线程才会终止
取消点:系统规定号的一些系统调用,我们可以粗略的理解为从用户区到内核区系统的切换
*/
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<unistd.h>
void *callback(void *arg){
printf("child thread id : %ld\n",pthread_self());
for(int i=0;i<5;i++){
printf("child : %d\n",i);
}
return NULL;
}
int main(){
//创建一个子线程
pthread_t tid;
int ret = pthread_create(&tid,NULL,callback,NULL);
if(ret!=0){
char *errstr=strerror(ret);
printf("error1 : %s\n",errstr);
}
//取消线程
pthread_cancel(tid);
for(int i=0;i<5;i++){
printf("%d\n",i);
}
//输出主线程和子线程的id
printf("tid %ld,main thread id : %ld\n",tid,pthread_self());
pthread_exit(NULL);
return 0;
}
3.6线程取消
最新推荐文章于 2024-06-23 18:54:52 发布
本文介绍了pthread_cancel函数在C语言多线程编程中的使用,它用于取消指定线程。线程并不会立即终止,而是在执行到一个取消点时才结束。取消点通常发生在系统调用处,即从用户空间到内核空间的转换。示例代码展示了如何创建并取消一个线程,以及如何在主线程和子线程中打印ID。
232

被折叠的 条评论
为什么被折叠?



