对于C++,是否存在"不等于比较和交换"或"fetch add on not equal"?

the*_*ang 1 c++ multithreading atomic c++11

还是以任何方式实施?

我们有一个原子:

std::atomic<int> val;
val = 0; 
Run Code Online (Sandbox Code Playgroud)

现在我想只在val不为零的情况下更新val.

if (val != 0) {
    // <- Caveat if val becomes 0 here by another thread.
    val.fetch_sub(1);  
}
Run Code Online (Sandbox Code Playgroud)

也许:

int not_expected = 0;
val.hypothetical_not_compare_exchange_strong(not_expected, val - 1);
Run Code Online (Sandbox Code Playgroud)

实际上上面也行不通,因为val可以val - 1在假设函数之间进行更新.

也许这个:

int old_val = val;
if (old_val == 0) {
    // val is zero, don't update val. some other logic.
} else {

    int new_val = old_val - 1;
    bool could_update = val.compare_exchange_strong(old_val, new_val);
    if (!could_update) {
        // repeat the above steps again.
    } 
}
Run Code Online (Sandbox Code Playgroud)

编辑:

val是一个计数器变量,与破坏对象无关.它应该是无符号的(因为计数永远不会是负数).

从线程A:如果发出类型2,则除非类型2计数器为0,否则不能发送类型1.

while(true) {
    if counter_1 < max_type_1_limit && counter_2 == 0 && somelogic:
        send_request_type1();
        counter_1++;

    if some logic && counter_2 == 0:
        send_request_type2();
        counter_2++;
}
Run Code Online (Sandbox Code Playgroud)

线程B&C:处理响应:

if counter_1 > 0:
     counter_1-- 
     // (provided that after this counter_1 doesn't reduce to negative)
else 
     counter_2--
Run Code Online (Sandbox Code Playgroud)

Mat*_*lia 5

实现不可用的原子操作的一般方法是使用CAS循环 ; 在你的情况下,它看起来像这样:

/// atomically decrements %val if it's not zero; returns true if it
/// decremented, false otherwise
bool decrement_if_nonzero(std::atomic_int &val) {
    int old_value = val.load();
    do {
        if(old_value == 0) return false;
    } while(!val.compare_exchange_weak(old_value, old_value-1));
    return true;
}
Run Code Online (Sandbox Code Playgroud)

因此,线程B&C将是:

if(!decrement_if_nonzero(counter_1)) {
    counter_2--
}
Run Code Online (Sandbox Code Playgroud)

并且线程A可以使用普通的原子加载/增量 - 线程A是唯一增加计数器的人,因此counter_1无论线程B和C做什么,它的检查都将保持在某个阈值以下.

我看到的唯一"奇怪"的东西就是counter_2修正逻辑 - 在线程B和C中,它在没有检查零的情况下递减,而在线程A中它只在它为零时递增 - 它看起来像一个bug.你的意思是在线程B/C中将它钳位到零吗?


话虽如此,原子是伟大的,所有,但更难以正确,所以如果我实现这种逻辑我开始用互斥量,然后移动到原子如果分析指出互斥是一个瓶颈.