来自优先选择
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n)
{
for (int cnt = 0; cnt < 100; ++cnt) {
while (lock.test_and_set(std::memory_order_acquire)) // acquire lock
; // spin <===================== no sleep
std::cout << "Output from thread " << n << '\n';
lock.clear(std::memory_order_release); // release lock
}
}
int main()
{
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}有理由不写自旋锁的同时循环std::this_thread::sleep_for?通常,当我写自旋锁时,我总是让线程进入睡眠状态,而不是让处理器在循环中一直运行线程。我做错了吗?
发布于 2021-03-07 11:29:46
自旋锁是指线程不处于休眠状态,而是运行(循环),直到满足特定条件为止。它不需要访问内核(除非您已经在内核中)。
使用this_thread::sleep_for将无法达到这个目的,即线程将由内核休眠,并在稍后由内核重新计划执行。这样的解决方案不再是自旋锁了。
https://stackoverflow.com/questions/66515829
复制相似问题