day7 线程的取消和清理

线程的取消

意义:随时杀掉一个线程

int pthread_cancel(pthread_t thread);

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

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

void pthread_testtcancel(void);

 代码实现:

#include 
#include 
#include 

void *func(void *arg) {
	printf("this is child thread\n");
	while(1) {
		sleep(5);
        pthread_testcancel();
	}
	pthread_exit("thread return");
}

int main() {
	pthread_t tid;
	void *retv;
	int i;
	pthread_create(&tid, NULL, func, NULL);
	sleep(5);
	pthread_cancel(tid);
	pthread_join(tid, &retv);

	while(1) {
		sleep(1);
	}
}

运行结果:

day7 线程的取消和清理_第1张图片

day7 线程的取消和清理_第2张图片

运行段错误:

可以使用gdb调试;

1、使用gdb编译代码;

gcc -g -o xxx xxx.c

 2、使用gdb运行程序;

gdb ./xxx

3、运行之后使run命令;

(gdb)run

等待出现Thread 1 "xxx" received signal SIGSEGV, Segmentation fault.

4、输入命令bt(打印调用栈)

(gdb) bt

#0  0x00007ffff783ecd0 in vfprintf () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007ffff78458a9 in printf () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00000000004007f9 in main () at xxx.c:21

确定段错误位置是xxx.c21行

设置取消属性

int pthread_setcancelstate(int state, int *oldstate);
PTHREAD_CANCEL_ENABLE  
PTHREAD_CANCEL_DISABLE

设置不能取消:PTHREAD_CANCEL_ENABLE

设置可以取消:PTHREAD_CANCEL_DISABLE

#include 
#include 
#include 

void *func(void *arg) {
	printf("this is child thread\n");

    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
//设置程序5秒之前不可取消

	while(1) {
		sleep(5);
        pthread_testcancel();
	}
    
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
//设置程序5秒之后可以取消

    while(1) {
		sleep(1);
	}
    
	pthread_exit("thread return");
}

int main() {
	pthread_t tid;
	void *retv;
	int i;
	pthread_create(&tid, NULL, func, NULL);
	sleep(1);
	pthread_cancel(tid);
	pthread_join(tid, &retv);

	while(1) {
		sleep(1);
	}
}

设置取消类型:

int pthread_setcanceltype(int type, int *oldtype);
PTHREAD_CANCEL_DEFERRED     
PTHREAD_CANCEL_ASYNCHRONOUS      

等到取消点才取消:PTHREAD_CANCEL_DEFERRED

目标线程会立即取消:PTHREAD_CANCEL_ASYNCHRONOUS

线程的清理

必要性:当线程非正常终止,需要清理一些资源

void pthread_cleanup_push(void (*routine) (void *), void *arg)
void pyhread_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_join 返回值,但不能触发pthread_cleanup_push里面的回调函数,所以我们结束线程尽量使用pthread_exit退出线程。

你可能感兴趣的:(LV6,并发程序设计,我的小白学习笔记,c语言,linux)