序言
Qt多线程同步常用类进行整理,然后区分它们的作用,能更好的去实现多线程应用程序。
QWaitCondition
The QWaitCondition class provides a condition variable for synchronizing threads.
QWaitCondition allows a thread to tell other threads that some sort of condition has been met. One or many threads can block waiting for a QWaitCondition to set a condition with wakeOne() or wakeAll(). Use wakeOne() to wake one randomly selected thread or wakeAll() to wake them all.
它可以用来阻塞某个线程,当满足某个条件时,可以提供过wakeOne 或者wakeAll,设置等待时间去激活线程。
bool QWaitCondition::wait(QMutex *lockedMutex, unsigned long time = ULONG_MAX)
Releases the lockedMutex and waits on the wait condition. The lockedMutex must be initially locked by the calling thread. If lockedMutex is not in a locked state, the behavior is undefined. If lockedMutex is a recursive mutex, this function returns immediately. The lockedMutex will be unlocked, and the calling thread will block until either of these conditions is met:
1. Another thread signals it using wakeOne() or wakeAll(). This function will return true in this case.
2. time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the event must be signalled). This function will return false if the wait timed out.
The lockedMutex will be returned to the same locked state. This function is provided to allow the atomic transition from the locked state to the wait state.
从锁态到等待状态为原子操作,当被激活后,又返回到原来的锁态。
以下用某个代码解释, 一个生产者线程、消费者线程去共享一个数据池,然后当数据池满后,阻塞生产者线程,如果数据池空后,阻塞消费者线程。
class Producer : public QThread
{
public:
Producer(QObject *parent = NULL) : QThread(parent)
{
}
protected:
void run();
};
class Consumer : public QThread
{
Q_OBJECT
public:
Consumer(QObject *parent = NULL) : QThread(parent)
{
}
protected:
void run();
};
#include <QWaitCondition>
#include <QMutex>
#include <QRandomGenerator>
#include <QDebug>
const int DataSize = 1000;
const int BufferSize = 20;
int buffer[BufferSize];
QWaitCondition bufferNotEmpty;
QWaitCondition bufferNotFull;
QMutex mutex;
int numUsedBytes = 0;
void Producer::run()
{
for (int i = 0; i < DataSize; ++i)
{
mutex.lock();
if (numUsedBytes == BufferSize)
bufferNotFull.wait(&mutex);
mutex.unlock();
buffer[i % BufferSize] = QRandomGenerator::global()->bounded(100);
qDebug() << " current Consumer thread id = " << QThread::currentThreadId() << " producer " << buffer[i % BufferSize];
mutex.lock();
++numUsedBytes;
bufferNotEmpty.wakeAll();
mutex.unlock();
}
}
void Consumer::run()
{
for (int i = 0; i < DataSize; ++i)
{
mutex.lock();
if (numUsedBytes == 0)
bufferNotEmpty.wait(&mutex);
mutex.unlock();
qDebug() << " current Consumer thread id = " << QThread::currentThreadId() << " take over " << buffer[i % BufferSize];
mutex.lock();
--numUsedBytes;
bufferNotFull.wakeAll();
mutex.unlock();
}
}
QMutex
The QMutex class provides access serialization b