Is this code threadsafe? Should I have volatile in the function sig? (ex: void Unlock() volatile {v=0;}) If it isn’t how do i make this threadsafe?
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
LocktoTryLocksince you are not calling CAS in a loop until it succeeds. TraditionallyLockoperations are supposed to block until the acquire succeeds.Regarding
volatile, the docs ofstd::atomicspecify (about the=operator):Then about
store:Then about
memory_order = std::memory_order_seq_cst:store
operation see the same order of memory accesses.
So no, you don’t need
volatilehere. Additionally,volatilehas weaker guarantees than the ones above (in fact,volatileis mostly useless in C++):