c++ - about spin lock -
i have questions in boost spinlock code :
class spinlock { public: spinlock() : v_(0) { } bool try_lock() { long r = interlockedexchange(&v_, 1); _readwritebarrier(); // 1. mean homecoming r == 0; } void lock() { (unsigned k = 0; !try_lock(); ++k) { yield(k); } } void unlock() { _readwritebarrier(); *const_cast<long volatile*>(&v_) = 0; // 2. why don't need utilize interlockedexchange(&v_, 0); } private: long v_; };
a readwritebarrier() "memory barrier" (in case both reads , writes), special instruction processor ensure instructions resulting in memory operations have completed (load
& store
operations - or in illustration x86 processors, opertion has memory operand @ either side). in particular case, create sure interlockedexchange(&v_,1) has completed before continue.
because interlockedexchange
less efficient (takes more interaction other cores in machine ensure other processor cores have 'let go' of value - makes no sense, since (in correctly working code) unlock
if hold lock, no other processor have different value cached we're writing on anyway), , volatile
write memory good.
c++ locking
No comments:
Post a Comment