c - 只有一个线程使用 memory_order_seq_cst 有用吗?

标签 c language-lawyer atomic memory-barriers stdatomic

在多线程程序中,如果只有一个线程使用它,您是否从 memory_order_seq_cst 得到任何保证,即您不会从较弱的顺序中得到保证?示例:

#include <stdatomic.h>

extern atomic_int x, y;

void doSomething(void);

void thread1(void) {
    atomic_store_explicit(&x, 1, memory_order_seq_cst);
    atomic_thread_fence(memory_order_seq_cst);
    if(atomic_load_explicit(&y, memory_order_seq_cst)) {
        doSomething();
    }
}

void thread2(void) {
    atomic_store_explicit(&y, 1, memory_order_release);
    atomic_thread_fence(memory_order_acq_rel);
    if(atomic_load_explicit(&x, memory_order_acquire)) {
        doSomething();
    }
}

如果 thread1thread2 并行运行,是否保证恰好一个总是调用 doSomething

最佳答案

我相信不会,如果只有一个线程使用它,它不会提供任何额外的保证。

seq-cst 和 acqure/release 之间的唯一区别是存在全局 seq-cst 操作顺序。

如果不执行 seq-cst 操作,其他线程将无法观察或影响此顺序。这条订单因此copies the "sequenced-before"使用 seq-cst 操作的单个线程的顺序,因为没有其他限制它。

关于c - 只有一个线程使用 memory_order_seq_cst 有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72439784/

相关文章:

c - 以下 c 程序的意外输出

c - 期待一份声明

c - 使用 free() 和 realloc() 时出错

c++ - std::declval<void>() 是一个有效的表达式吗?

c++ - 好友声明 : Is this a bug in clang?

c - 如何理解glibc交叉引用?

c++ - 如果没有显式限定名称,如何调用纯虚函数?

c++ - 调整 std::vector<std::atomic bool> 的大小,将 true 分配给所有原子书

c++ - const 对象的无锁重载和共享

linux - perl sysopen 可以打开文件进行原子写入吗?