簡體   English   中英

Qt同步障礙?

[英]Qt synchronization barrier?

Qt是否等同於同步障礙? 第一個N-1呼叫者wait阻止的類型和第N個呼叫者wait導致它們全部釋放。

不,但您可以使用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();
    }
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM