Qt是否等同于同步障碍? wait
的第一个N-1调用者和wait
的第N个调用者阻塞的类型导致它们全部释放。
最佳答案
不,但是您可以使用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();
}
...
}
关于c++ - Qt同步障碍?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9637374/