TTAS Lock C++11 实现

 1 template<class Lock>
 2 class Lock_guard{
 3 private:
 4     Lock lock;
 5 public:
 6     explicit Lock_guard(Lock& lock){
 7         this->lock = lock;
 8         this->lock.lock();
 9     }
10     ~Lock_guard(){
11         this->lock.unlock();
12     }
13     Lock_guard(const Lock_guard&) = delete;
14     Lock_guard& operator = (const Lock_guard&) = delete;
15 };
16 
17 class TTASLock{
18 private:
19     atomic<bool> state;
20 public:
21     void lock(){
22         while (true){
23             while (state.load()){};
24             if (!state.exchange(true, std::memory_order_relaxed))
25                 return;
26         }
27     }
28     void unlock(){
29         state.store(false);
30     }
31 };

 

你可能感兴趣的:(Lock)