代码下载
a.zip
-
#include<pthread.h>
-
int pthread_cancel(pthread_t tid)
线程取消属性没有包含在pthread_attr_t结构中,所以调用
pthread_cancel(pthread_t tid)不需要初始化pthread_attr_t结构;
-
#include<pthread.h>
-
int pthread_setcanceltypeint type,int *oldtype)
当设置type为PTHREAD_CANCEL_ASYNCHRONOUS异步取消时,线程可以在不遇到取消点时就可以取消,就是说一被cancel就停止运行
若type设置为PTHREAD_CANCEL_DEFERRED延迟取消时,线程必须要等到取消点才能取消。
关于pthread_setcancelstate就不多说了,在书上331页有讲解。
一个取消的例子
-
#include <pthread.h>
-
#include <stdio.h>
-
#include<unistd.h>
-
-
pthread_t tid1,tid2;
-
-
void *fn_1(void *arg)
-
{
-
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
-
printf("Thread 1 is running...\n");
-
while(1)
-
{
-
printf("running...\n");
-
sleep(1);
-
}
-
printf("I was cancelled by other thread\n");
-
pthread_exit((void*)1);
-
}
-
-
void *fn_2(void*arg)
-
{
-
printf("Thread 2 is running...I will cancel thread 1 after 5 seconds\n");
-
sleep(5);
-
pthread_cancel(tid1);
-
pthread_exit((void*)2);
-
}
-
-
int main()
-
{
-
pthread_create(&tid1,NULL,fn_1,NULL);
-
pthread_create(&tid2,NULL,fn_2,NULL);
-
pthread_join(tid1,NULL);
-
pthread_join(tid2,NULL);
-
return 0;
-
}
运行结果:
-
[vibe@localhost code]$ ./a
-
Thread 1 is running...
-
running...
-
Thread 2 is running...I will cancel thread 1 after 5 seconds
-
running...
-
running...
-
running...
-
running...
阅读(1648) | 评论(0) | 转发(0) |