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
你是如何測試性能的?在鎖上有沒有實際的爭用? –