一个关于Lightweight Mutex 和 Heavyweight Mutex的实验

来源:互联网 发布:linux常用软件下载 编辑:程序博客网 时间:2024/04/30 15:32

  Reprint:http://preshing.com/20111124/always-use-a-lightweight-mutex

In multithreaded programming, we often speak of locks (also known as mutexes). But a lock is only a concept. To actually use that concept, you need an implementation. As it turns out, there are many ways to implement a lock, and those implementations vary wildly in performance.

The Windows SDK provides two lock implementations for C/C++: the Mutexand the Critical Section. (As Ned Batchelder points out, Critical Section is probably not the best name to give to the lock itself, but we’ll forgive that here.)

The Windows Critical Section is what we call a lightweight mutex. It’s optimized for the case when there are no other threads competing for the lock. To demonstrate using a simple example, here’s a single thread which locks and unlocks a Windows Mutex exactly one million times.

HANDLE mutex = CreateMutex(NULL, FALSE, NULL);for (int i = 0; i < 1000000; i++){    WaitForSingleObject(mutex, INFINITE);    ReleaseMutex(mutex);}CloseHandle(mutex);

Here's the same experiment using a Windows Critical Section.

CRITICAL_SECTION critSec;InitializeCriticalSection(&critSec);for (int i = 0; i < 1000000; i++){    EnterCriticalSection(&critSec);    LeaveCriticalSection(&critSec);}DeleteCriticalSection(&critSec);

If you insert some timing code around the inner loop, and divide the result by one million, you'll find the average time required for a pair of lock/unlock operations in both cases. I did that, and ran the experiment on two different processors. The results:

The Critical Section is 25 times faster. As Larry Osterman explains, the Windows Mutex enters the kernel every time you use it, while the Critical Section does not. The tradeoff is that you can't share a Critical Section between processes. But who cares? Most of the time, you just want to protect some data within a single process. (It is actually possible to share a lightweight mutex between processes - just not using a Critical Section. See Roll Your Own Lightweight Mutex for example.)

Now, suppose you have a thread which acquires a Critical Section 100000 times per second, and there are no other threads competing for the lock. Based on the above figures, you can expect to pay between 0.2% and 0.6% in lock overhead. Not too bad! At lower frequencies, the overhead becomes negligible.



原创粉丝点击