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

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

    I have no idea if this is going to be of help, but the following snippet from Herb Sutter's implementation of a concurrent queue uses a spinlock based on atomics:

    std::atomic consumerLock;
    
    {   // the critical section
        while (consumerLock.exchange(true)) { }  // this is the spinlock
    
        // do something useful
    
        consumerLock = false;  // unlock
    }
    

    In fact, the Standard provides a purpose-built type for this construction that is required to have lock-free operations, std::atomic_flag. With that, the critical section would look like this:

    std::atomic_flag consumerLock;
    
    {
        // critical section
    
        while (consumerLock.test_and_set()) { /* spin */ }
    
        // do stuff
    
        consumerLock.clear();
    }
    

    (You can use acquire and release memory ordering there if you prefer.)

提交回复
热议问题