phtread_cancel函数用于取消线程,但不是实时的

文章讲述了在某些线程函数中,自定义的取消点无效时,如何使用pthread_testcancel检查并处理pthread_cancel不生效的情况。同时提到,当线程被pthread_join回收且已由pthread_detach处理时,可能会导致特定错误和行为。

 

如上图所示,线程函数中没有取消点(一般是一些系统调用----man 7 pthreads查看,自定义函数是无效的),则使用pthread_cancle函数不生效。 

解决方法:可以添加pthread_testcancle();

通过pthread_join回收的线程已经被phread_cancel了的话,返回值是-1;

pthread_join回收的线程已经被phread_detach了的话,会报错,错误号是22;

#include<stdio.h> #include<unistd.h> #include<pthread.h> void cleanup(void *arg){ printf("cleanup,arg=%s\n",(char *)arg); } void *func (void *arg) { printf("this is child pthread\n"); // pthread_exit("pthread return\n"); phtread_cleanup_push(cleanup,"abcd"); while(1){ sleep(1); } pthread_exit("thread return"); pthread_cleanup_pop(1); } int main (){ pthread_t tid; void *retv; pthread_create(&tid,NULL,func,NULL); sleep(1); pthread_cancel(tid); pthread_join(tid,&retv); // printf("thread ret=%s\n",(char *)retv); while(1){ sleep(1); } } 我在Ubuntu运行代码时处出现一下报错请你帮我指出并修改: root@ubuntu:~/jincheng/day4# gcc -o cleanup cleanup.c -lpthread cleanup.c: In function ‘func’: cleanup.c:12:2: warning: implicit declaration of function ‘phtread_cleanup_push’ [-Wimplicit-function-declaration] phtread_cleanup_push(cleanup,"abcd"); ^ In file included from cleanup.c:3:0: cleanup.c: At top level: cleanup.c:17:2: error: expected identifier or ‘(’ before ‘while’ pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected declaration specifiers or ‘...’ before ‘&’ token pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘if’ pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘}’ token pthread_cleanup_pop(1); ^ cleanup.c:17:2: error: expected identifier or ‘(’ before ‘while’ pthread_cleanup_pop(1); ^ cleanup.c:19:1: error: expected identifier or ‘(’ before ‘}’ token }
最新发布
07-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值