问题描述
#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();
}
}
在while循环std::this_thread::sleep_for
中不写入自旋锁是否有原因?通常当我写自旋锁时,我总是让线程进入睡眠状态,而不是让处理器一直在循环中运行线程。我做错了吗?
解决方法
spinlock 是当线程不进入睡眠状态,而是运行(循环)直到满足特定条件。它不涉及内核之旅(除非您已经在内核中)。
使用 this_thread::sleep_for
会违背目的,即线程将被 内核 置于睡眠状态,并在稍后由 内核 重新安排执行在。这样的解决方案不再是自旋锁了。