利用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);
  }
};

引用


shiyang6017
158 声望59 粉丝

引用和评论

0 条评论