Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a Qt equivalent of a barrier for synchronization? The type where the first N-1 callers to wait block and the Nth caller to wait causes them all to release.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
186 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, but you can use QWaitCondition to make these barriers:

#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.wait(&mutex);
        else
            condition.wakeAll();
        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;
};

Usage example code:

class MyThread : public QThread {
public:
    MyThread(Barrier barrier, QObject *parent = 0) 
    : QThread(parent), barrier(barrier) {}
    void run() {
        qDebug() << "thread blocked";
        barrier.wait();
        qDebug() << "thread released";
    }
private:
    Barrier barrier;
};

int main(int argc, char *argv[])
{   
    ...
    Barrier barrier(5);

    for(int i=0; i < 5; ++i) {
        MyThread * thread = new MyThread(barrier);
        thread->start();
    }
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...