boost库在工作(19)线程之四

从前面也看到使用锁boost::mutex时,如果不小心就会死锁,这样要费心费力去维护这样的代码,在boost库里提供同一个函数递归调用时使用的锁boost::recursive_mutex,当同一个线程调用时,碰到相同已经上锁的锁时,还可以继续往下执行。这时就不用担心同一个线程调用不同的函数时造成死锁了。在前面的例子死锁的代码,当换成这个锁之后,就不会再有死锁了,代码如下:

// boost_012.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>

//全局锁。
boost::recursive_mutex g_mutexAll;
//递归锁不会死锁
void First(void)
{
	std::cout << "First In" << std::endl;

	boost::lock_guard<boost::recursive_mutex> autoLock(g_mutexAll);
	std::cout << "First Out" << std::endl;
}

void Second(void)
{
	std::cout << "Second In" << std::endl;

	boost::lock_guard<boost::recursive_mutex> autoLock(g_mutexAll);
	std::cout << "Second Out" << std::endl;

	//这里递归访问同一个锁,使用递归锁后不会死锁。
	First();
}

//线程组运行的函数
//软件开发人员: 蔡军生  2013-02-15
//QQ: 9073204
void Run(int nVal)
{
	//
	int nTemp = nVal * nVal;

	//下面输出需要加锁,不能多个线程共享输出。
	static boost::mutex mutexCout;
	boost::lock_guard<boost::mutex> autoLock(mutexCout);
	std::cout << "thread Run: [" << nVal << "] " << nTemp << std::endl;

	//
	Second();
}

int _tmain(int argc, _TCHAR* argv[])
{
	//定义一个线程组对象。
	boost::thread_group threadGroup;	

	//设置最大的线程个数。
	const int nMaxCount = 5;
	//循环地创建N个线程。
	for (int i = 0; i < nMaxCount; ++i)
	{
		threadGroup.create_thread(boost::bind(Run, i));
	}

	//等所有线程退出。
	threadGroup.join_all();

	system("PAUSE");

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caimouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值