目录
1 QSemaphore
#include <QSemaphore>
#include <QThread>
#include <QDebug>
QSemaphore sem1(1);
QSemaphore sem2(0);
QSemaphore sem3(0);
class Thread1 : public QThread
{
public:
void run() override
{
sem1.acquire();
// 执行线程1的任务
qDebug()<<"Thread1";
sem2.release();
}
};
class Thread2 : public QThread
{
public:
void run() override
{
sem2.acquire();
// 执行线程2的任务
qDebug()<<"Thread2";
sem3.release();
}
};
class Thread3 : public QThread
{
public:
void run() override
{
sem3.acquire();
// 执行线程3的任务
qDebug()<<"Thread3";
sem1.release();
}
};
int main()
{
Thread1 thread1;
Thread2 thread2;
Thread3 thread3;
thread2.start();
QThread::msleep(1000);
thread1.start();
thread3.start();
thread1.wait();
thread2.wait();
thread3.wait();
return 0;
}
在这个例子中,QSemaphore被用来控制线程的执行顺序。线程1首先开始执行,因为sem1的初始值为1。当线程1完成后,它会释放sem2,这允许线程2开始执行。同样,当线程2完成后,它会释放sem3,这允许线程3开始执行。当线程3完成后,它会释放sem1,这允许线程1再次执行。这个过程可以无限循环,直到你决定停止线程。
2 QMutex和QWaitCondition
#include <QMutex>
#include <QWaitCondition>
#include <QThread>
#include <QDebug>
QMutex mutex;
QWaitCondition condition;
int a = 1;
class Thread1 : public QThread
{
public:
void run() override
{
QMutexLocker locker(&mutex);
while (a != 1)
condition.wait(&mutex);
// 执行线程1的任务
qDebug()<<"Thread1 run";
a = 2;
condition.wakeAll();
}
};
class Thread2 : public QThread
{
public:
void run() override
{
QMutexLocker locker(&mutex);
while (a != 2)
condition.wait(&mutex);
// 执行线程2的任务
qDebug()<<"Thread2 run";
a = 3;
condition.wakeAll();
}
};
class Thread3 : public QThread
{
public:
void run() override
{
QMutexLocker locker(&mutex);
while (a != 3)
condition.wait(&mutex);
// 执行线程3的任务
qDebug()<<"Thread3 run";
a = 1;
condition.wakeAll();
}
};
int main()
{
Thread1 thread1;
Thread2 thread2;
Thread3 thread3;
thread2.start();
QThread::msleep(100);
thread1.start();
thread3.start();
thread1.wait();
thread2.wait();
thread3.wait();
return 0;
}
在这个例子中,QMutex和QWaitCondition被用来控制线程的执行顺序。每个线程在开始执行任务之前都会获取互斥锁,并检查当前应该执行的线程编号。如果线程编号不匹配,线程会等待条件变量。当线程完成任务后,它会更新线程编号并唤醒所有等待的线程。
这种方法的优点是它可以处理更复杂的线程同步问题,例如,当线程的执行顺序不是固定的,或者当线程需要等待多个条件时。
3 QFuture
#include <QtConcurrent>
#include <QFuture>
void function1() {
// 执行线程1的任务
qDebug()<<"function1";
}
void function2() {
// 执行线程2的任务
qDebug()<<"function2";
}
void function3() {
// 执行线程3的任务
qDebug()<<"function3";
}
int main() {
QFuture<void> future1 = QtConcurrent::run(function1);
future1.waitForFinished();
QFuture<void> future2 = QtConcurrent::run(function2);
future2.waitForFinished();
QFuture<void> future3 = QtConcurrent::run(function3);
future3.waitForFinished();
return 0;
}
在这个例子中,QtConcurrent::run用于在一个新的线程中运行一个函数,它返回一个QFuture对象,你可以使用QFuture::waitForFinished来等待线程完成。这种方法的优点是它非常简单,但是它只适用于你需要按顺序执行的线程,并且每个线程只执行一次的情况。