¿Barrera de sincronización Qt?

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.

preguntado el 09 de marzo de 12 a las 16:03

1 Respuestas

No, pero puedes usar 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();
    }
    ...
}

respondido 09 mar '12, 19:03

This was my alternate approach, but thanks, you've saved me some coding. - edA-qa mort-ora-y

Much obliged, @alexisdm! Just a note, in the BarrierData constructor, you the param you pass into the constructor has the same name as the variable. - Adri CS

@Adri: I think that was on purpose. It is perfectly legal and saves you from inventing silly conventions. - Lennart Rolland

counter is never reset or increased so this barrier will only work once. Looking at implementation in boost it seems there is something missing! boost.org/doc/libs/1_40_0/boost/thread/barrier.hpp - Lennart Rolland

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.