使用recursive_mutex来代替mutex

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值