#include <QApplication>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QDebug>
QMutex mutex1_;
QMutex mutex2_;
QMutex mutex3_;
QWaitCondition cond1_;
QWaitCondition cond2_;
QWaitCondition cond3_;
class myThread1:public QThread{
public:
myThread1() {}
protected:
void run(){
for (int i = 0; i < 10; i++) {
mutex1_.lock();
cond1_.wait(&mutex1_);
mutex1_.unlock();
qDebug() << "A\t" << currentThreadId() << "\t" << getpid();
cond2_.wakeAll();
}
}
};
class myThread2:public QThread{
public:
myThread2() {}
protected:
void run(){
for (int i = 0; i < 10; i++) {
mutex2_.lock();
cond2_.wait(&mutex2_);
mutex2_.unlock();
qDebug() << "B\t" << currentThreadId() << "\t" << getpid();
cond3_.wakeAll();
}
}
};
class myThread3:public QThread{
public:
myThread3() {}
protected:
void run(){
for (int i = 0; i < 10; i++) {
mutex3_.lock();
cond3_.wait(&mutex3_);
mutex3_.unlock();
qDebug() << "C\t" << currentThreadId() << "\t" << getpid();
cond1_.wakeAll();
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
myThread1* thread1 = new myThread1();
myThread2* thread2 = new myThread2();
myThread3* thread3 = new myThread3();
thread1->start();
thread2->start();
thread3->start();
QThread::sleep(1);
cond1_.wakeAll(); // 确保线程启动后执行
return a.exec();
}
输出:
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008
A 0x2ae0 22008
B 0x2adc 22008
C 0x5288 22008