主要思想就是两个QSemaphore,线程1打印时,获取semaphore1,结束时释放semaphore2,线程2打印
时获取semaphore2,结束时释放semaphore1,semaphore2初始状态为获取
workthread.h
#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include <QObject>
#include <QThread>
#include <QSemaphore>
class WorkThread : public QThread
{
Q_OBJECT
public:
explicit WorkThread(QObject *parent = nullptr);
void Init(int startValue, int increment, QSemaphore *semaphoreSelf, QSemaphore *semaphore2);
public:
void run() override;
private:
int startValue;
int increment;
QSemaphore *semaphoreSelf;
QSemaphore *semaphore2Other;
signals:
public slots:
};
#endif // WORKTHREAD_H
workthrad.cpp
#include "workthread.h"
#include <QDebug>
WorkThread::WorkThread(QObject *parent) : QThread(parent)
{
}
void WorkThread::Init(int startValue, int increment, QSemaphore *semaphoreSelf, QSemaphore *semaphore2)
{
this->startValue = startValue;
this->increment = increment;
this->semaphoreSelf = semaphoreSelf;
this->semaphore2Other = semaphore2;
}
void WorkThread::run()
{
qDebug()<<"Start";
for (int i = startValue; i <= 100; i += increment)
{
semaphoreSelf->acquire(); // 获取信号量,如果没有可用的,则线程阻塞
qDebug() << i;
semaphore2Other->release();
}
}
main.cpp
#include <QCoreApplication>
#include <QSemaphore>
#include <QDebug>
#include <QThread>
#include "workthread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSemaphore semaphore1(1);
QSemaphore semaphore2(1);
semaphore2.acquire();
WorkThread thread1;
thread1.Init(0,2,&semaphore1,&semaphore2);
WorkThread thread2;
thread2.Init(1,2,&semaphore2,&semaphore1);
qDebug()<<"start";
thread1.start();
thread2.start();
thread1.wait();
thread2.wait();
return a.exec();
}