C++11: atomic 头文件

0

利用CAS实现自旋锁

class spin_mutex {
private:
  std::atomic<bool> flag = ATOMIC_VAR_INIT(false);
public:
  spin_mutex() = default;
  spin_mutex(const spin_mutex&) = delete;
  spin_mutex& operator= (const spin_mutex&) = delete;
  void lock() {
    bool expected = false;
    while(!flag.compare_exchange_strong(expected, true))
      expected = false;
  }
  void unlock() {
    flag.store(false);
  }
};

引用

你可能感兴趣的

载入中...