[英]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): 关于
volatile
, std::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
:
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.