从前面也看到使用锁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;
}