c - 原子比较(不等于)和交换

标签 c multithreading gcc compare-and-swap

我想使用原子比较和交换,而不是等于,我只想在内存位置不等于旧值时交换。在 C 中可以吗?

最佳答案

这个怎么样:

void compare_and_swap_if_not_equal(word_t const required_non_value, word_t const new_value, word_t* ptr_to_shared_variable) { 
    for (;;) {
        word_t const snapshot_value = *ptr_to_shared_variable;
        if (required_non_value == snapshot_value) {
            break;
            // or (sleep and) 'continue;', if you want to wait for the stored value to be different 
            // -- but you might of course miss a transient change to a different state and back.
        } else { 
            if (compare_and_swap_if_equal(ptr_to_shared_variable, snapshot_value, new_value)) {
                // we know the stored value was different; if this 'theory' still matches reality: swap! done!
                break;
            }
        }
    }
}

未经测试。未编译。使用'const'是因为我喜欢这样:)。 'word_t' 是一个类型占位符,我不知道真正的类型应该是什么。而且我不知道在 stdatomic.h 中如何调用“compare_and_swap_if_equal”。

(补充)atomic_compare_exchange_weak() 是门票。出于某种原因,它需要一个指向“预期”参数的指针,因此您必须将上面的代码修改为

if (atomic_compare_exchange_weak(ptr_to_shared_variable, &snapshot_value, new_value)) ...

“弱”版本应该在上面的代码中工作;虚假地返回“false”只会在循环中增加另一次旅行。仍未编译,未经测试;不要在家里依赖这个代码。

关于c - 原子比较(不等于)和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12755130/

相关文章:

linux - 目标代码文件 ctr1.o 在 gcc 编译器中有什么作用?

c++ - 将 Mysql C API 用于 C++ 代码

c - libsasl2 在 OSX Yosemite 上是否损坏?缺少 sasl_client_done

c - 运算符有什么用!!在C?

python - 为什么我的 Python C 扩展会泄漏内存?

python - 使用 pulp 在 Python 中实现多线程

java - 为什么添加 Thread.sleep 会使我的 Akka TestKit 单元测试通过?

php - linux 正确标志传递 gcc mcrypt.h 位置

c# - C++ 新手,想在 MFC 应用程序中创建后台线程

c - gtk_window_set_ressized 将窗口设置为最小