QT中使用多线程循环打印ABC

#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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值