2012-03-09 54 views

回答

14

沒有,但你可以使用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(); 
    } 
    ... 
} 
+0

這是我的另一種方法,但感謝,你救了我一些編碼。 – 2012-03-10 09:08:47

+0

非常感謝,@alexisdm!請注意,在BarrierData構造函數中,您傳遞給構造函數的參數與變量具有相同的名稱。 – 2013-05-02 15:49:10

+0

@Adri:我認爲這是有意的。這是完全合法的,並且可以使你避免發明愚蠢的約定。 – 2016-09-15 21:48:35