gpt4 book ai didi

c++ - 有没有一种简单的方法可以在 C++0x 中实现 AutoResetEvent?

转载 作者:可可西里 更新时间:2023-11-01 18:21:06 31 4
gpt4 key购买 nike

我知道我之前问过这个问题:What is the C++ equivalent for AutoResetEvent under Linux?

但是,我了解到在 C++0x 中,线程库变得更加简单,所以我想再次提出这个问题,有没有一种简单的方法可以在 C++0x 中实现 AutoResetEvent?

最佳答案

这是对 accepted answer to your first question 的翻译使用 C++11 工具:

#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdio.h>

class AutoResetEvent
{
public:
explicit AutoResetEvent(bool initial = false);

void Set();
void Reset();

bool WaitOne();

private:
AutoResetEvent(const AutoResetEvent&);
AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable
bool flag_;
std::mutex protect_;
std::condition_variable signal_;
};

AutoResetEvent::AutoResetEvent(bool initial)
: flag_(initial)
{
}

void AutoResetEvent::Set()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = true;
signal_.notify_one();
}

void AutoResetEvent::Reset()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = false;
}

bool AutoResetEvent::WaitOne()
{
std::unique_lock<std::mutex> lk(protect_);
while( !flag_ ) // prevent spurious wakeups from doing harm
signal_.wait(lk);
flag_ = false; // waiting resets the flag
return true;
}


AutoResetEvent event;

void otherthread()
{
event.WaitOne();
printf("Hello from other thread!\n");
}


int main()
{
std::thread h(otherthread);
printf("Hello from the first thread\n");
event.Set();

h.join();
}

输出:

Hello from the first thread
Hello from other thread!

更新

在下方评论tobsen请注意,AutoResetEvent 具有 signal_.notify_all() 而不是 signal_.notify_one() 的语义。我没有更改代码,因为 accepted answer to the first question使用了 pthread_cond_signal 而不是 pthread_cond_broadcast 并且我首先声明这是对该答案的忠实翻译。

关于c++ - 有没有一种简单的方法可以在 C++0x 中实现 AutoResetEvent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8538575/

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