#include
#include
#include
#include
void *thread1(void *ptr)
{
//void *status1;
printf(" this is thread1, tid is %lu\n",
pthread_self());
sleep(5); //pthread_exit(status1);
}
void *thread2(void *ptr)
{
int ret4;
sleep(1); ret4 =
pthread_cancel(*((pthread_t*)ptr));
if(ret4<0)
printf("can not cancel thread %lu\n",
*((pthread_t*)ptr));
else
printf("has cancel the thread
%lu\n",*((pthread_t*)ptr));
}
int main(int argc, char** argv) {
pthread_t tid1,tid2;
int ret1,ret2,ret3;
int time1,time2;
void* status;
time1 = 30;
ret1=
pthread_create(&tid1,NULL,thread1,(void*)time1);
ret2=
pthread_create(&tid2,NULL,thread2,(void*)&tid1); ret3=
pthread_join(tid1,&status); if(status == PTHREAD_CANCELED)
{
printf(" thread1 is canceled!\n");
}
else
{
printf(" thread1 run 5 seconds, then
end!\n");
}
sleep(10);
return (EXIT_SUCCESS);
}
结果:
this is thread1, tid is 3083447184
has cancel the thread 3083447184
//pthread2在执行pthread_cancel(pthread1)时,pthread1还处于sleep状态,故可以cancel
thread1 is canceled!//pthread1的状态是cancel
如果在thread2中sleep(6)秒,则会
this is thread1, tid is 3083447184
thread1 run 5 seconds,then
end!//pthread2在执行pthread_cancel(pthread1)之前,pthread1已经结束并返回给主线程
has cancel the thread 3083447184//仍可以cancel
与pthread_cancel函数有关系