这段代码转载自:http://www.cnblogs.com/xiedan/archive/2009/12/16/1625977.html
#include<iostream>
#include<unistd.h>
#include<pthread.h>
#define INT_MAX 1e9
using namespace std;
pthread_t pid[3];
void* thread_run_1(void* arg)
{
cout<<"Now in the thread 1"<<endl;
int sum = 0;
int state, oldstate;
state = PTHREAD_CANCEL_DEFERRED;//PTHREAD_CANCEL_ASYNCHRONOUS
pthread_setcanceltype(state, &oldstate);
cout<<"oldstate is "<<(oldstate==0?"DEFERRED":"ASYNCHRONOUS")<<endl;
cout<<"state is "<<(state==0?"DEFERRED":"ASYNCHRONOUS")<<endl;
//耗时间的循环
for (int i = 1; i<=INT_MAX; ++i);
cout<<"before testcancel"<<endl;
pthread_testcancel();
cout<<"after testcancel"<<endl;
cout<<"thread 1 done!"<<endl;
}
void* thread_run_2(void* arg)
{
cout<<"Now in the thread 2"<<endl;
pthread_cancel(pid[1]);
sleep(2);
cout<<"thread 2 done!"<<endl;
}
int main()
{
pid[0] = pthread_self();
if (pthread_create(&pid[1],NULL,thread_run_1,NULL) != 0)
{
cout<<"error create thread 1"<<endl;
return -1;
}
if (pthread_create(&pid[2],NULL,thread_run_2,NULL) != 0)
{
cout<<"error create thread 2"<<endl;
return -1;
}
sleep(5);
cout<<"Main thread done!"<<endl;
}
1.当state = PTHREAD_CANCEL_ASYNCHRONOUS;
运行结果:
brian@ubuntu:~/test$ g++ pthread_cancel.cpp -lpthread -o cancel
brian@ubuntu:~/test$ ./cancel
Now in the thread 1
oldstate is DEFERRED
state is ASYNCHRONOUS
Now in the thread 2
thread 2 done!
Main thread done!
2.当state = PTHREAD_CANCEL_DEFERRED;
运行结果:
brian@ubuntu:~/test$ g++ pthread_cancel.cpp -lpthread -o cancel
brian@ubuntu:~/test$ ./cancel
Now in the thread 1
oldstate is DEFERRED
state is DEFERRED
Now in the thread 2
thread 2 done!
before testcancel
<疑问:为什么没有输出Main thread done!>
难道pthread_cancel()只在state = PTHREAD_CANCEL_DEFERRED时有用?
当state =PTHREAD_CANCEL_ASYNCHRONOUS时,thead1就直接结束了?
希望有人给我解答一下。谢谢!!!