Writing a (spinning) thread barrier using c++11 atomics

后端 未结 7 2168
花落未央
花落未央 2020-12-28 22:48

I\'m trying to familiarize myself with c++11 atomics, so I tried writing a barrier class for threads (before someone complains about not using existing classes: this is more

7条回答
  •  一个人的身影
    2020-12-28 23:39

    Here is a simple version of mine :

    // spinning_mutex.hpp
    #include 
    
    
    class spinning_mutex
    {
    private:
        std::atomic lockVal;
    public:
        spinning_mutex() : lockVal(false) { };
    
        void lock()
        {
            while(lockVal.exchange(true) );
        } 
    
        void unlock()
        {
            lockVal.store(false);
        }
    
        bool is_locked()
        {
            return lockVal.load();
        }
    };
    

    Usage : (from std::lock_guard example)

    #include 
    #include 
    #include "spinning_mutex.hpp"
    
    int g_i = 0;
    spinning_mutex g_i_mutex;  // protects g_i
    
    void safe_increment()
    {
        std::lock_guard lock(g_i_mutex);
        ++g_i;
    
        // g_i_mutex is automatically released when lock
        // goes out of scope
    }
    
    int main()
    {
        std::thread t1(safe_increment);
        std::thread t2(safe_increment);
    
        t1.join();
        t2.join();
    }
    

提交回复
热议问题