79446755

Date: 2025-02-17 22:48:33
Score: 2
Natty:
Report link

I would have liked to comment but I can't because of insufficient reputation. However, note that the top voted answer is suffering from spurious wakeups (see also Can QWaitCondition spuriously wake up?). So a better variant of the answer would be:

#include <QMutex>
#include <QWaitCondition>
#include <QSharedPointer>

// Data "pimpl" class (not to be used directly)
class BarrierData
{
public:
    BarrierData(int count) : count(count) {}

    void wait() {
        mutex.lock();
        --count;
        if (count == 0) {
            condition.wakeAll();
        } else {
            while(count != 0) {
                condition.wait(&mutex);
            }
         }
            
        mutex.unlock();
    }
private:
    Q_DISABLE_COPY(BarrierData)
    int count;
    QMutex mutex;
    QWaitCondition condition;
};

class Barrier {
public:
    // Create a barrier that will wait for count threads
    Barrier(int count) : d(new BarrierData(count)) {}
    void wait() {
        d->wait();
    }

private:
    QSharedPointer<BarrierData> d;
};
Reasons:
  • Blacklisted phrase (1): to comment
  • RegEx Blacklisted phrase (1.5): reputation
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: cwiede