• 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;
    }
  • 相关阅读:
    《代码整洁之道》读书笔记六
    第九周总结
    《构建之法》读后感(五)
    学习进度条-第十二周
    3. 统计数字
    《构建之法》读后感(四)
    学习进度条-第十一周
    4. 丑数 II
    《构建之法》读后感(三)
    学习进度条-第十周
  • 原文地址:https://www.cnblogs.com/tongyishu/p/13195099.html
Copyright © 2020-2023  润新知