spin_lock自旋锁
Posted tongyishu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spin_lock自旋锁相关的知识,希望对你有一定的参考价值。
#include <string>
#include <iostream>
#include <thread>
#include <atomic>
class spin_lock{
private:
std::atomic<bool> flag = ATOMIC_VAR_INIT(false);
public:
spin_lock() = default;
spin_lock(const spin_lock&) = delete;
spin_lock& operator = (const spin_lock&) = delete;
void lock() {
bool expected = false;
while (!flag.compare_exchange_strong(expected, true)) {
expected = false;
}
}
void unlock() {
flag.store(false);
}
};
int g_test = 0;
spin_lock g_spinlck;
void work(int& thread_no) {
for (int i = 0;i < 1000;i++) {
g_spinlck.lock();
g_test++;
std::cout << "thread_no : " << thread_no << " ; g_test : " << g_test << std::endl;
g_spinlck.unlock();
}
}
int main()
{
int thread_no0 = 0;
int thread_no1 = 1;
std::thread thd1(work, std::ref(thread_no0));
std::thread thd2(work, std::ref(thread_no1));
thd1.join();
thd2.join();
return 0;
}
以上是关于spin_lock自旋锁的主要内容,如果未能解决你的问题,请参考以下文章