两个例子:
阻塞例子:
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread_fun(void *arg)
{
int i=1;
printf("thread start \n");
while(1)
{
i++;
}
return (void *)0;
}
int main()
{
void *ret=NULL;
int iret=0;
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
sleep(1);
pthread_cancel(tid);//取消线程
pthread_join(tid, &ret);
printf("thread 3 exit code %p\n", ret);
return 0;
}
非阻塞例子:
#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thread_fun(void *arg)
{
int i=1;
printf("thread start \n");
while(1)
{
i++;
//pthread_testcancel(); //没有系统调用的时候需要它停掉线程. 否则线程会一直阻塞.
//printf("%d \n", i); //系统调用函数,则不用上面函数将其停掉.
//sleep(1);
}
return (void *)0;
}
int main()
{
void *ret=NULL;
int iret=0;
pthread_t tid;
pthread_create(&tid,NULL,thread_fun,NULL);
sleep(5);
pthread_cancel(tid);//取消线程
pthread_join(tid, &ret);
printf("thread 3 exit code %p\n", ret);
return 0;
}
将while循环中的注释掉的三句,任何一句打开,都会停止阻塞.
原因是: pthread_cancel向另一线程发终止信号。系统并不会马上关闭被取消线程,只有在被取消线程下次系统调用时,才会真正结束线程。如果线程里面没有执行系统调用,可以使用pthread_testcancel解决。
必须要有系统调用, 如果没有系统调用,则调用pthread_testcancel函数.
pthread_testcancel()函数用来在当前线程创建一个“可取消点”。如果当前线程是不能取消的,则这个函数无效。pthread_setcancelstate, pthread_setcanceltype, pthread_testcancel - set cancelability state这三个函数用来设置线程是否可以被其他线程调用pthread_cancel函数取消/终止。
拷贝链接:
http://blog.csdn.net/i_am_jojo/article/details/7594174
http://blog.csdn.net/huangshanchun/article/details/47420961