gpt4 book ai didi

c++ - 为什么在通知 condition_variable 之前需要获取锁来修改共享的 "atomic"变量

转载 作者:可可西里 更新时间:2023-11-01 17:44:29 26 4
gpt4 key购买 nike

<分区>

根据cppreference.com :

The thread that intends to modify the variable has to

  1. acquire a std::mutex (typically via std::lock_guard)
  2. perform the modification while the lock is held
  3. execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

我不是很明白,为什么修改原子变量需要锁。请看下面的代码片段:

static std::atomic_bool s_run {true};
static std::atomic_bool s_hasEvent {false};
static std::mutex s_mtx;
static std::condition_variabel s_cv;


// Thread A - the consumer thread
function threadA()
{
while (s_run)
{
{
std::unique_lock<std::mutex> lock(s_mtx);
s_cv.wait(lock, [this]{
return m_hasEvents.load(std::memory_order_relaxed);
});
}

// process event
event = lockfree_queue.pop();
..... code to process the event ....
}
}


// Thread B - publisher thread
function PushEvent(event)
{
lockfree_queque.push(event)
s_hasEvent.store(true, std::memory_order_release);
s_cv.notify_one();
}

在 PushEvent 函数中,我没有获取 s_mtx,因为 s_hasEvent 是一个原子变量,队列是无锁的。没有获取 s_mtx 锁的问题是什么?

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