接上一篇,在多线程中基本上都需要解决线程同步问题,本篇文章主要将介绍如何使用QMutex/ QMutexLocker互斥量来同步线程。
首先,先回顾下Qt官网QThreads general usage介绍,其中有一段基本上介绍了其使用方法,如下:
The main thing in this example to keep in mind when using a QThread is that it's not a thread. It's a wrapper around a thread object. This wrapper provides the signals, slots and methods to easily use the thread object within a Qt project. To use it, prepare a QObject subclass with all your desired functionality in it. Then create a new QThread instance, push the QObject onto it using moveToThread(QThread*) of the QObject instance and call start() on the QThread instance. That's all. You set up the proper signal/slot connections to make it quit properly and such, and that's all.
现在,直接上售票的小例子:
Step1. 按Qt介绍的用法:先创建一个继承QObject的类,把要执行的函数包装进里面:
.h 文件代码如下:
#ifndef TICKETSELLER_H
#define TICKETSELLER_H
#include <QObject>
#include <QThread>
#include <QMutex>
#include <string>
class TicketSeller : public QObject
{
public:
TicketSeller();
~TicketSeller();
public slots:
void sale();
public:
int* tickets;
QMutex* mutex;
std::string name;
};
#endif // TICKETSELLER_H
.cpp 文件代码如下:
#include "ticketseller.h"
#include <iostream>
TicketSeller::TicketSeller()
{
tickets = 0;
mutex = NULL;
}
TicketSeller::~TicketSeller()
{
}
void TicketSeller::sale()
{
while((*tickets) > 0)
{
mutex->lock();
std::cout << name << " : " << (*tickets)-- << std::endl;
mutex->unlock();
}
/*while((*tickets) > 0)
{
QMutexLocker locker(mutex);
std::cout << name << " : " << (*tickets)-- << std::endl;
locker.unlock();
}*/
}
Step2. 按Qt介绍的用法:创建一个实例,使用moveToThread将对象移至QThread内,并连接信号槽,最后调用start()方法:
main.cpp 文件代码如下:
#include <QCoreApplication>
#include <QMutex>
#include <QThread>
#include <string>
#include "ticketseller.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int ticket = 100;
QMutex mutex;
/*创建设置线程1*/
//创建线程1
QThread t1;
TicketSeller seller1;
//设置线程1
seller1.tickets = &ticket;
seller1.mutex = &mutex;
seller1.name = "seller1";
//将对象移动到线程
seller1.moveToThread(&t1);
/*创建设置线程2*/
//创建线程2
QThread t2;
TicketSeller seller2;
seller2.tickets = &ticket;
seller2.mutex = &mutex;
seller2.name = "seller2";
//将对象移动到线程
seller2.moveToThread(&t2);
QObject::connect(&t1, &QThread::started, &seller1, &TicketSeller::sale);
QObject::connect(&t2, &QThread::started, &seller2, &TicketSeller::sale);
t1.start();
t2.start();
return a.exec();
}
QT 中使用 QMutex/ QMutexLocker 比Window API CreateMutex 配合 WaitForSingleObject 同步线程要简单得多。