spin_lock自旋锁

当线程在获取锁的时候,如果锁已经被其它线程占用,那么该线程将循环等待(而不是进入休眠状态),不断地尝试是否能够成功获取锁,直到成功获取到锁才会退出循环。

循环待的过程中,线程会一直处于活跃状态,占用cpu资源。

使用c++ automic原子类实现一个简单的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;
}
原文地址:https://www.cnblogs.com/tongyishu/p/13195099.html