测试结论是std::mutex明显效率要比CRITICAL_SECTION效率更高。以下代码是对一个变量进行多线程++操作,到一定数量后退出线程,然后计算整个过程耗时。测试结果显示std::mutex耗时明显低。另外测试发现std::mutex是不可重入的。
#include <iostream>
#include <mutex>
#include <windows.h>
#include <thread>
#pragma comment(lib, "Winmm.lib")
using namespace std;
std::mutex gMutex;
CRITICAL_SECTION gSec;
volatile int nMutexCount = 0;
volatile int nSecCount = 0;
int nMaxCount = 1000000;
void TestSec()
{
while (true)
{
EnterCriticalSection(&gSec);
nSecCount++;
if (nSecCount >= nMaxCount)
{
LeaveCriticalSection(&gSec);
break;
}
LeaveCriticalSection(&gSec);
}
}
void TestMutex()
{
while (true)
{
std::lock_guard<std::mutex> lk(gMutex);
nMutexCount++;
if (nMutexCount >= nMaxCount)
{
break;
}
}
}
#include <vector>
vector<int> a{