WinAPI下有WaitForSingleObject()和ReleaseMutex()函数对。还有Interlocked *()函数系列。我决定在捕获单个互斥锁和交换互锁变量之间检查性能。WaitForSingleObject vs Interlocked *
HANDLE mutex;
WaitForSingleObject(mutex, INFINITE);
// ..
ReleaseMutex(mutex);
// 0 unlocked, 1 locked
LONG lock = 0;
while(InterlockedCompareExchange(&lock, 1, 0))
SwitchToThread();
// ..
InterlockedExchange(&lock, 0);
SwitchToThread();
我测量了这两种方法之间的性能,发现使用Interlocked *()的速度快了大约38%。为什么这样?
这里是我的性能测试:
#include <windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
LONG interlocked_variable = 0; // 0 unlocked, 1 locked
int run = 1;
DWORD WINAPI thread(LPVOID lpParam)
{
while(run)
{
while(InterlockedCompareExchange(&interlocked_variable, 1, 0))
SwitchToThread();
++(*((unsigned int*)lpParam));
InterlockedExchange(&interlocked_variable, 0);
SwitchToThread();
}
return 0;
}
int main()
{
unsigned int num_threads;
cout << "number of threads: ";
cin >> num_threads;
unsigned int* num_cycles = new unsigned int[num_threads];
DWORD s_time, e_time;
s_time = GetTickCount();
for(unsigned int i = 0; i < num_threads; ++i)
{
num_cycles[i] = 0;
HANDLE handle = CreateThread(NULL, NULL, thread, &num_cycles[i], NULL, NULL);
CloseHandle(handle);
}
_getch();
run = 0;
e_time = GetTickCount();
unsigned long long total = 0;
for(unsigned int i = 0; i < num_threads; ++i)
total += num_cycles[i];
for(unsigned int i = 0; i < num_threads; ++i)
cout << "\nthread " << i << ":\t" << num_cycles[i] << " cyc\t" << ((double)num_cycles[i]/(double)total) * 100 << "%";
cout << "\n----------------\n"
<< "cycles total:\t" << total
<< "\ntime elapsed:\t" << e_time - s_time << " ms"
<< "\n----------------"
<< '\n' << (double)(e_time - s_time)/(double)(total) << " ms\\op\n";
delete[] num_cycles;
_getch();
return 0;
}
互斥锁是跨进程同步的内核对象,因此每个锁定/解锁都涉及上下文切换。 [见此处](http://msdn.microsoft.com/en-us/magazine/cc163726.aspx)进行相关讨论。 –
据我所知,互斥锁更适合多个进程之间的同步。您可能还想尝试一个关键部分。 – Paul
你是如何测试性能的?在锁上有没有实际的争用? –