a.zip点击(此处)折叠或打开
-
#include<pthread.h>
- int pthread_cancel(pthread_t tid)
点击(此处)折叠或打开
-
#include<pthread.h>
- int pthread_setcanceltypeint type,int *oldtype)
若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...