gpt4 book ai didi

c++ - WaitForSingleObject 与互锁*

转载 作者:行者123 更新时间:2023-11-30 00:51:48 26 4
gpt4 key购买 nike

在 WinAPI 下有 WaitForSingleObject() 和 ReleaseMutex() 函数对。还有 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;
}

最佳答案

WaitForSingleObject 不必更快。它涵盖范围更广的同步场景,特别是您可以等待不“属于”您的进程的句柄,因此进程间同步。考虑到所有这些因素,根据您的测试,它慢了 38%。

如果您的进程中包含所有内容并且每一纳秒都很重要,InterlockedXxx 可能是更好的选择,但它绝对不是绝对优越的选择。

此外,您可能还想看看 Slim Reader/Writer (SRW) Locks应用程序接口(interface)。您也许可以完全基于 InterlockedXxx 构建类似的类/函数,性能略好,但关键是使用 SRW 后,您可以开箱即用,并记录了行为,无论如何都稳定且具有不错的性能。

关于c++ - WaitForSingleObject 与互锁*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com