thread-cancel

来源:互联网 发布:ubuntu qt环境搭建 编辑:程序博客网 时间:2024/06/13 23:43

1、设置一个接收请求并且延迟

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <pthread.h>void* thread_function(void* p);int main(){int res;pthread_t a_thread;void* thread_result;res = pthread_create(&a_thread, NULL, thread_function, NULL);if(0 != res){perror("thread creation failed!");exit(EXIT_FAILURE);}sleep(3);//3 secondsprintf("Cancel thread...\n");res = pthread_cancel(a_thread);if(0 != res){perror("thread cancelation failed!");exit(EXIT_FAILURE);}printf("Waiting for thread to finish...\n");pthread_join(a_thread, &thread_result);if(0 != res){perror("thread join failed!");exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);return 0;}void * thread_function(void* p){int i, res;int old_state;int old_type;//set cancel state, PTHREAD_CANCEL_ENABLE - 允许取消,PTHREAD_CANCEL_DISABLE, 不允许取消res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);if(0 != res){perror("thread pthread_setcancelstate failed!");exit(EXIT_FAILURE);}//set cancel type//PTHREAD_CANCEL_ASYNCHRONOUS: 接收到请求后立即执行//PTHREAD_CANCEL_DEFERRED:接收到取消请求后等待到诸如函数pthread_join, pthread_cond_wait, pthread_cond_timedwait, pthread_testcancel, sem_wait,sigwait时,才退出res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_type);if(0 != res){perror("thread pthread_setcanceltype failed!");exit(EXIT_FAILURE);}printf("thread_function is running..\n");for(i = 0; i < 10; ++i){printf("thread function is still running(%d)...\n",i);sleep(1);}exit(EXIT_SUCCESS);}


测试结果:

@ubuntu:~/Desktop/workspace/thread$ cc -D_REENTANT -o thread_cancel thread_cancel.c -lpthread


@ubuntu:~/Desktop/workspace/thread$ ./thread_cancel 


thread_function is running..
thread function is still running(0)...
thread function is still running(1)...
thread function is still running(2)...
Cancel thread...
Waiting for thread to finish...

2、如果把res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);改为res = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);

则子线程不接收主线程的取消请求,子线程一直运行完for后才退出,测试结果为

thread_function is running..
thread function is still running(0)...
thread function is still running(1)...
thread function is still running(2)...
Cancel thread...
Waiting for thread to finish...
thread function is still running(3)...
thread function is still running(4)...
thread function is still running(5)...
thread function is still running(6)...
thread function is still running(7)...
thread function is still running(8)...
thread function is still running(9)...

3、如果把1中的res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_type);改为res = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_type);  子线程将立即被取消,测试结果为:

thread_function is running..
thread function is still running(0)...
thread function is still running(1)...
thread function is still running(2)...
Cancel thread...
Waiting for thread to finish...



0 0
原创粉丝点击