我有一个具有最小值和最大值的原子整数变量。两个线程更新变量,一个增加它,另一个减少它。如果递增会使值超过最大值,则线程阻塞并等待条件变量。当值达到最小值时,减量也会发生同样的事情。当值递减并且旧值是最大值时,递减线程应该通知递增线程,并且在递增时应该以相反的方式发生同样的事情。
递减函数体:
if (atomic_var.load(std::memory_order_acquire) == minimum) {
std::unique_lock<std::mutex> lk(mutex);
if (atomic_var.load(std::memory_order_acquire) == minimum) {
//we have hit the minimum so we have to wait for the other thread to increase the variable
condition_var.wait(lk, [&]() {
return atomic_var.load(std::memory_order_relaxed) > minimum;
});
}
//do stuff
std::atomic_fetch_sub_explicit(&atomic_var, 1u, std::memory_order_release);
lk.unlock();
condition_var.notify_all();
return;
}
//do stuff
if (std::atomic_fetch_sub_explicit(&atomic_var, 1u, std::memory_order_release) == maximum) {
//we have hit the maximum so the other thread might be waiting
std::atomic_thread_fence(std::memory_order_acquire);
condition_var.notify_all();
}
//adding condition_var.notify_all() here fixes the problem but I'm afraid
//that causes a bit too great performance penalty when it could be easily avoided
我应该使用哪些内存顺序进行这些检查?我当前的实现似乎导致死锁......
编辑:将所有内存顺序更改为 std::memory_order_seq_cst 似乎并没有解决问题。