对于Windows,关键部分的权重比互斥轻。
互斥可以在进程之间共享,但是总是导致对内核的系统调用,这会产生一些开销。
关键部分只能在一个进程中使用,但具有的优势是,它们仅在争用的情况下才切换到内核模式-
无竞争的获取(这是常见的情况)非常快。在争用的情况下,它们进入内核以等待某些同步原语(例如事件或信号量)。
我编写了一个快速的示例应用程序,比较了两者之间的时间。在我的系统中,要进行1,000,000次无竞争的获取和释放,互斥体将占用一秒钟的时间。关键部分大约需要50毫秒才能完成1,000,000次采集。
这是测试代码,如果互斥是第一个或第二个,我会运行此代码并获得相似的结果,因此我们看不到任何其他效果。
HANDLE mutex = CreateMutex(NULL, FALSE, NULL);CRITICAL_SECTION critSec;InitializeCriticalSection(&critSec);LARGE_INTEGER freq;QueryPerformanceFrequency(&freq);LARGE_INTEGER start, end;// Force pre into memory, so we don't see any effects of paging.EnterCriticalSection(&critSec);LeaveCriticalSection(&critSec);QueryPerformanceCounter(&start);for (int i = 0; i < 1000000; i++){ EnterCriticalSection(&critSec); LeaveCriticalSection(&critSec);}QueryPerformanceCounter(&end);int totalTimeCS = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);// Force pre into memory, so we don't see any effects of paging.WaitForSingleObject(mutex, INFINITE);ReleaseMutex(mutex);QueryPerformanceCounter(&start);for (int i = 0; i < 1000000; i++){ WaitForSingleObject(mutex, INFINITE); ReleaseMutex(mutex);}QueryPerformanceCounter(&end);int totalTime = (int)((end.QuadPart - start.QuadPart) * 1000 / freq.QuadPart);printf("Mutex: %d CritSec: %dn", totalTime, totalTimeCS);


