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

后端 未结 7 2167
花落未央
花落未央 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:51

    Why not use std::atomic_flag (from C++11)?

    http://en.cppreference.com/w/cpp/atomic/atomic_flag

    std::atomic_flag is an atomic boolean type. Unlike all specializations of std::atomic, it is guaranteed to be lock-free.

    Here's how I would write my spinning thread barrier class:

    #ifndef SPINLOCK_H
    #define SPINLOCK_H
    
    #include 
    #include 
    
    class SpinLock
    {
    public:
    
        inline SpinLock() :
            m_lock(ATOMIC_FLAG_INIT)
        {
        }
    
        inline SpinLock(const SpinLock &) :
            m_lock(ATOMIC_FLAG_INIT)
        {
        }
    
        inline SpinLock &operator=(const SpinLock &)
        {
            return *this;
        }
    
        inline void lock()
        {
            while (true)
            {
                for (int32_t i = 0; i < 10000; ++i)
                {
                    if (!m_lock.test_and_set(std::memory_order_acquire))
                    {
                        return;
                    }
                }
    
                std::this_thread::yield();  // A great idea that you don't see in many spinlock examples
            }
        }
    
        inline bool try_lock()
        {
            return !m_lock.test_and_set(std::memory_order_acquire);
        }
    
        inline void unlock()
        {
            m_lock.clear(std::memory_order_release);
        }
    
    private:
    
        std::atomic_flag m_lock;
    };
    
    #endif
    

提交回复
热议问题