(C++) atomic_flag的使用

使用示例

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

int main(int argc, char** argv) {
  constexpr size_t kLoopNum = 10;
  std::atomic_flag lock = ATOMIC_FLAG_INIT;
  auto thd_func = [kLoopNum, &lock]() {
    while (lock.test_and_set(std::memory_order_acquire)) { // 自旋锁
      ;
    }

    const auto tid = std::this_thread::get_id();
    for (size_t i = 0; i < kLoopNum; i++) {
      std::cout << "tid " << tid << " working id " << i << std::endl;
    }

    std::cout << "thread exit " << tid << std::endl;
    lock.clear(std::memory_order_release);
  };

  std::vector<std::thread> thds(3);
  for (auto& thd : thds) {
    thd = std::thread(thd_func);
  }

  for (auto& thd : thds) {
    thd.join();
  }

  return 0;
}

输出

tid 139922263504448 working id 0
tid 139922263504448 working id 1
tid 139922263504448 working id 2
tid 139922263504448 working id 3
tid 139922263504448 working id 4
tid 139922263504448 working id 5
tid 139922263504448 working id 6
tid 139922263504448 working id 7
tid 139922263504448 working id 8
tid 139922263504448 working id 9
thread exit 139922263504448
tid 139922255111744 working id 0
tid 139922255111744 working id 1
tid 139922255111744 working id 2
tid 139922255111744 working id 3
tid 139922255111744 working id 4
tid 139922255111744 working id 5
tid 139922255111744 working id 6
tid 139922255111744 working id 7
tid 139922255111744 working id 8
tid 139922255111744 working id 9
thread exit 139922255111744
tid 139922246719040 working id 0
tid 139922246719040 working id 1
tid 139922246719040 working id 2
tid 139922246719040 working id 3
tid 139922246719040 working id 4
tid 139922246719040 working id 5
tid 139922246719040 working id 6
tid 139922246719040 working id 7
tid 139922246719040 working id 8
tid 139922246719040 working id 9
thread exit 139922246719040
``

## 说明
1. atomic_flag使用自旋锁,即忙等。好处是处在用户空间不用陷入kernel。
2. 猜测针对ARM应该有性能上的影响,因为忙等轮询期间每次查询需要使用acquire/release,seq_cst等内存模型,导致data cache清空。
3. 经过简单测试,内存fence指令对ARM影响很大,但是针对原本就是强内存序的x86影响不大。
posted @ 2022-11-22 17:36  山岚2013  阅读(249)  评论(0编辑  收藏  举报