搜索

(C++) atomic_flag的使用


发布时间: 2022-11-24 20:01:00    浏览次数:36 次

使用示例

#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影响不大。
免责声明 (C++) atomic_flag的使用,资源类别:文本, 浏览次数:36 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 08:01:00。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/vaughnhuang/p/16915899.html