recursive_mutex比起mutex,最主要的好处就是降低了死锁的可能性。
但是发现很多人更喜欢用mutex,理由是效率更高。其实recursive的效率已经足够快了。
以下是两个平台(硬件,操作系统都不同)下两者的对比测试,测试时间是5s:
mutex :
27156244
99336454
recursive_mutex:26266666
62064554
======================================测试代码===================================================
#include <iostream>
#include <string>
#include <boost/thread.hpp>
using namespace std;
using namespace boost;
#ifdef WIN32
#
include <Windows.h>
#else
#
include <unistd.h>
#endif
typedef unsigned int uint32;
inline void sleepms(int ms)
{
#ifdef WIN32
::Sleep( uint32(ms) );
#else
::usleep(ms * 1000);
#endif
}
volatile bool run_flag = false;
boost::mutex mtx;
boost::recursive_mutex rmtx;
void test_mutex()
{
int cnt = 0;
while(run_flag)
{
boost::mutex::scoped_lock lock(mtx);
cnt ++;
}
cout << cnt << endl;
}
void test_recursive_mutex()
{
int cnt = 0;
while(run_flag)
{
boost::recursive_mutex::scoped_lock lock(rmtx);
cnt ++;
}
cout << cnt << endl;
}
int main(int ac, char *av[])
{
{
run_flag = true;
boost::thread thr(test_recursive_mutex);
sleepms(5000);
run_flag = false;
thr.join();
}
{
run_flag = true;
boost::thread thr(foo2);
sleepms(5000);
run_flag = false;
thr.join();
}
return 0;
}
但是发现很多人更喜欢用mutex,理由是效率更高。其实recursive的效率已经足够快了。
以下是两个平台(硬件,操作系统都不同)下两者的对比测试,测试时间是5s:
mutex :
recursive_mutex:26266666
======================================测试代码===================================================
#include <iostream>
#include <string>
#include <boost/thread.hpp>
using namespace std;
using namespace boost;
#ifdef WIN32
#
#else
#
#endif
typedef unsigned int uint32;
inline void sleepms(int ms)
{
#ifdef WIN32
#else
#endif
}
volatile bool run_flag = false;
boost::mutex mtx;
boost::recursive_mutex rmtx;
void test_mutex()
{
}
void test_recursive_mutex()
{
}
int main(int ac, char *av[])
{
}