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

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

    It looks needlessly complicated. Try this simpler version (well, I haven't tested it, I just meditated on it:))) :

    #include <atomic>
    
    class spinning_barrier
    {
    public:
        spinning_barrier (unsigned int n) : n_ (n), nwait_ (0), step_(0) {}
    
        bool wait ()
        {
            unsigned int step = step_.load ();
    
            if (nwait_.fetch_add (1) == n_ - 1)
            {
                /* OK, last thread to come.  */
                nwait_.store (0); // XXX: maybe can use relaxed ordering here ??
                step_.fetch_add (1);
                return true;
            }
            else
            {
                /* Run in circles and scream like a little girl.  */
                while (step_.load () == step)
                    ;
                return false;
            }
        }
    
    protected:
        /* Number of synchronized threads. */
        const unsigned int n_;
    
        /* Number of threads currently spinning.  */
        std::atomic<unsigned int> nwait_;
    
        /* Number of barrier syncronizations completed so far, 
         * it's OK to wrap.  */
        std::atomic<unsigned int> step_;
    };
    

    EDIT: @Grizzy, I can't find any errors in your first (C++11) version and I've also run it for like a hundred million syncs with two threads and it completes. I've run it on a dual-socket/quad-core GNU/Linux machine though, so I'm rather inclined to suspect your option 3. - the library (or rather, its port to win32) is not mature enough.

    0 讨论(0)
提交回复
热议问题