线程的取消和清理

目录

线程取消函数-pthread_cancel

运行段错误调试

线程的清理-pthread_cleanup_push


线程取消函数-pthread_cancel

意义是随时可以杀掉一个线程

int pthread_cancel (pthread_t thread);

注意:线程的取消要有取消点才可以,不是说取消就可以取消,线程的取消点主要是阻塞的系统调用

运行段错误调试

可以使用gdb调试

编译要用gcc -g test.c -o test

使用gdb运行代码,gdb ./youapp

(gdb)run

等待出现Thread 1 "pcancel" receivel signal SIGSEGV, Segmentation fault.

输入命令ht(打印调用栈)

(gdb) bt

#00x00007ffff783ecd0 in vfprintf () from /lib/x86_64-linux-gnu/libc.so.6

#10x00007ffff78458a9 in printf () from /lib/x86_64-linux-gnu/libc.so.6

#20x00000000004007f9 in main () at pcancel.c:21

确定段错误位置是pcancel.c 21行

如果没有取消点,手动设置一个

void pthread_testcancel(void);

设置取消使能或禁止

int pthread_setcancelstate(int state,int *oldstate);

PTHREAD_CANCEL_ENABLE//设置线程可以被取消

PTHREAD_CANCEL_DISABLE//设置线程不被取消

int pthread_setcanceltype(int type, int *oldtype);

PTHREAD_CANCEL_DEFERRED等到取消点才取消

PTHREAD_CANCEL_ASYNCHRONOUS目标线程会立即取消

线程的清理-pthread_cleanup_push

void pthread_cleanup_push(void (*routint)(void *),void *arg);

void pthread_cleanup_pop(int execute);

routine函数呗执行条件

  1. 被pthread_cancel取消掉
  2. 执行pthread_exit
  3. 非0参数执行pthread_cleanup_pop();

注意:

  1. 这两个函数本质是两个宏,必须配对使用,及时pthread_cleanup_pop不会被执行到也必须写上,否则编译错误。
  2. pthread_cleanup_pop()被执行且参数为0,pthread_cleanup_push回调函数routine不会被执行
  3. pthread_cleanup_push和pthread_cleanup_pop 可以写多对,routine执行顺序正好相反
  4. 线程内的return可以结束线程,但是不能触发pthread_cleanup_push函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值