Qt同步障碍? [英] Qt synchronization barrier?

查看:139
本文介绍了Qt同步障碍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有Qt等同于同步的障碍?第一个N-1调用等待阻塞,第N个调用等待使它们全部释放的类型。

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.

推荐答案

不,但您可以使用 QWaitCondition

#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;
};

使用示例代码:

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();
    }
    ...
}

这篇关于Qt同步障碍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆