关于pthread_testcancel()的疑问

这段代码转载自: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就直接结束了?

希望有人给我解答一下。谢谢!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值