我对__atomic_seq_cst的理解正确吗? (i' d喜欢用它写一个哑光+ atomics)
为了好玩,我写了自己的线程库,由我和一两个朋友使用。我要写的第一件事是静音
,看来我正在生成我想要的组件。 __ atomic_fetch_add
似乎生成锁定XADD
和__ atomic_exchange
似乎会生成XCHG
(不是CMPXCHG)。我两者都将__ atomic_seq_cst
(现在我坚持下去),
如果我使用__ atomic_seq_cst
gcc或clang会理解这些功能是否同步?如果我写lock();全局++; unlock();
是否有任何编译器在锁定/解锁功能之前或之后移动global ++;
?我是否需要调用__ atomic_thread_fence(__ atomic_seq_cst);
或__ sync_synchronize();
出于任何原因? (他们似乎在x86-64上做同样的事情)。 https://gcc.gnu.org.org.org.org/wiki/wiki/wiki/atomic/atomic/gccmm/atomicsysync 似乎暗示我的理解是正确的,但是很容易误解文档,有时我想知道范围是否在这些规则中起作用。
我认为使用这些内在的锁定/解锁之间的代码行为将与pthread Mutex锁/解锁相同的方式?
For fun I'm writing my own threading library used by me and a friend or two. First thing I'd like to write is a mutex
It appears I'm generating the assembly I want. __atomic_fetch_add
seems to generate lock xadd
and __atomic_exchange
seems to generate xchg
(not cmpxchg). I use both with __ATOMIC_SEQ_CST
(for now I'll stick to that)
If I am using __ATOMIC_SEQ_CST
will gcc or clang understand these are synchronizing function? If I write lock(); global++; unlock();
will any compilers move global++;
before or after the lock/unlock function? Do I need to call __atomic_thread_fence(__ATOMIC_SEQ_CST);
or __sync_synchronize();
for any reason? (they seem to do the same thing on x86-64). https://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync seems to suggest my understanding is correct but its easy to misread documentation and I sometimes wonder if scope plays a part in these rules.
I think using those intrinsic the behavior of code in between a lock/unlock will act the same way as a pthread mutex lock/unlock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这就是这些原语具有内存顺序语义的全部原因。
记忆排序语义的成就完成了两件事:(1)确保编译器发出指令,其中包括防止CPU重新排序的适当障碍; (2)确保编译器优化不会以障碍禁止的方式将代码超过这些说明。
他们不会。同样,这就是能够指定内存排序的重点。
不在这种情况下,不。
Yes, that is the entire reason for these primitives to have memory ordering semantics.
The memory ordering semantics accomplish two things: (1) ensure that the compiler emits instructions that include the appropriate barriers to prevent reordering by the CPU; (2) ensure that compiler optimizations do not move code past those instructions in ways that the barrier should forbid.
They will not. Again, that is the whole point of being able to specify memory ordering.
Not in this setting, no.