gpt4 book ai didi

c++ - WaitForSingleObject 不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 00:22:10 25 4
gpt4 key购买 nike

请看下面的代码:

#include <windows.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateMutex(NULL, FALSE, "abc");
if (!_mutex)
throw std::runtime_error("CreateMutex failed");

if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");

printf("Must lock here\n");

if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");

printf("Why come here????\n");
return 0;
}

我不知道为什么控制台打印出来:

Must lock here
Why come here???

互斥锁不起作用吗?我只想显示结果

Must lock here

并在打印上面的文本后阻塞。

最佳答案

如果您想要一个像您描述的那样运行的同步原语,您可以改用自动重置事件。

 #include <windows.h>
#include <stdexcept>
#include <stdio.h>
int main(int argc, char* argv[])
{
HANDLE _mutex = ::CreateEvent(NULL, FALSE, TRUE, NULL);
// auto reset // initially signalled
if (!_mutex)
throw std::runtime_error("CreateEvent failed");

if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");
// unsignalled now

printf("Must lock here\n");

// will block forever until someone calls SetEvent
if (::WaitForSingleObject(_mutex, INFINITE) != WAIT_OBJECT_0)
throw std::runtime_error("WaitForSingleObject failed");

printf("Why come here????\n");
return 0;
}

关于c++ - WaitForSingleObject 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3552931/

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