简体   繁体   English

这个简单的(原子)锁定线程是否安全?

[英]Is this simple (atomic) lock thread safe?

Is this code threadsafe? 这段代码是否安全? Should I have volatile in the function sig? 我应该在函数sig中有volatile吗? (ex: void Unlock() volatile {v=0;} ) If it isn't how do i make this threadsafe? (例如: void Unlock() volatile {v=0;} )如果不是我如何使这个线程安全?

class SimpleLock {
    std::atomic<int> v;
public:
    bool try_lock() { int z=0; return v.compare_exchange_strong(z, 1); }
    void lock() { while(try_lock()==false) std::this_thread::yield(); }
    void unlock() {v=0;}
};

Yes, it is thread-safe, although you could rename Lock to TryLock since you are not calling CAS in a loop until it succeeds. 是的,它是线程安全的,虽然你可以将Lock重命名为TryLock因为你没有在循环中调用CAS直到它成功。 Traditionally Lock operations are supposed to block until the acquire succeeds. 传统上, Lock操作应该阻塞,直到获取成功为止。

Regarding volatile , the docs of std::atomic specify (about the = operator): 关于volatilestd::atomic 的文档指定(关于=运算符):

Atomically assigns a value t to the atomic variable. 原子上为原子变量赋值t。 Equivalent to store(desired). 相当于商店(所需)。

Then about store : 关于store

void store( T desired, memory_order = std::memory_order_seq_cst ); void store(T desired,memory_order = std :: memory_order_seq_cst);

Then about memory_order = std::memory_order_seq_cst : 然后关于memory_order = std::memory_order_seq_cst

  • No writes in the writer thread can be reordered after the atomic store 在原子存储之后,编写器线程中的写入不能重新排序
  • No reads in the reader thread can be reordered before the atomic load. 在原子加载之前,读取器线程中的读取不能重新排序。
  • The synchronization is established between all atomic operations tagged std::memory_order_seq_cst. 在标记为std :: memory_order_seq_cst的所有原子操作之间建立同步。 All threads using such atomic operation see the same order of memory accesses. 使用此类原子操作的所有线程都看到相同的内存访问顺序。

So no, you don't need volatile here. 所以不,你不需要在这里volatile Additionally, volatile has weaker guarantees than the ones above (in fact, volatile is mostly useless in C++): 另外, volatile保证比上面的保证弱(事实上, volatile在C ++中几乎没用):

Within a thread of execution, accesses (reads and writes) to all volatile objects are guaranteed to not be reordered relative to each other, but this order is not guaranteed to be observed by another thread, since volatile access does not establish inter-thread synchronization. 在执行的一个线程中,对所有易失性对象的访问(读取和写入)保证不会相对于彼此重新排序,但是这个顺序不能保证被另一个线程观察到,因为易失性访问不会建立线程间同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM