gpt4 book ai didi

c - Mutex 不同步 C++

转载 作者:行者123 更新时间:2023-11-30 14:53:21 25 4
gpt4 key购买 nike

我有 2 个进程。第一个向另一个发送一些数据,同步每个 Action 。它实际上发送的数据如下:

 Process : A sends 1
Process : B receives 1
Process : A sends 2
Process : B receives 2

问题是,当我运行进程 A 时,它从头开始发送所有数据,我看到如下内容:

 Process : A sends 1
Process : A sends 2
Process : A sends 3
Process : B receives 3

我做了如下:

  Process A
HANDLE mutex;
mutex = CreateMutex(NULL, FALSE, TEXT("mutex1"));
if (mutex == INVALID_HANDLE_VALUE) {
_tprintf(TEXT("Create mutex error !.\n"), GetLastError());
return 1;
}
for (int i = 0; i < sender_length;i++) {
WaitForSingleObject(mutex,INFINITE);
sendToB(data);
ReleaseMutex(mutex);
}

CloseHandle(mutex);

B 流程如下所示:

 Process B:

HANDLE mutex;

mutex = OpenMutex(SYNCHRONIZE, FALSE, TEXT("mutex1"));

if (mutex == INVALID_HANDLE_VALUE) {
_tprintf(TEXT("Mutex error ! \n"), GetLastError());
return 1;
}
for (int i = 0; i < sender_length;i++) {
WaitForSingleObject(mutex,INFINITE);
receiveFromA(data);
ReleaseMutex(mutex);
}

CloseHandle(mutex);

最佳答案

我不确定这是你的问题,但我认为很有可能它至少是一个贡献者:Windows 锁已经有一段时间不公平了。请参阅 Joe Duffy 的文章 Anti-convoy locks in Windows Server 2003 SP1 and Windows Vista了解一些详细信息。

Duffy 特别针对互斥体说了以下内容(突出显示是我添加的):

Of course, Windows locks are still a teensy bit fair. The wait lists for mutually exclusive locks are kept in FIFO order, and the OS always wakes the thread at the front of such wait queues. ... Now when a lock becomes unowned, a FIFO waking algorithm is still used, but the lock is immediately marked as unavailable. Another thread can sneak in and take the lock before the woken thread is even scheduled

另一个线程可以是刚刚释放锁的线程。在您的代码中,释放互斥锁的线程所做的下一件事就是尝试重新获取互斥锁,这是一个很好的位置。

关于c - Mutex 不同步 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232319/

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