Qt waitCondition使用例子
时间: 2023-07-10 13:21:08 浏览: 216
Qt5开发及实例-CH1203.rar,Qt5使用QWaitCondition类解决生产者和消费者问题的代码
下面是一个使用 QWaitCondition 的例子,其中有一个线程不断向一个共享的缓冲区中写入数据,另一个线程从缓冲区中读取数据,如果缓冲区为空,则等待直到有数据可读。
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
const int BUFFER_SIZE = 10;
class Buffer
{
public:
Buffer()
: m_readIndex(0)
, m_writeIndex(0)
, m_dataCount(0)
{
}
void write(int data)
{
QMutexLocker locker(&m_mutex);
while (m_dataCount == BUFFER_SIZE) {
m_notFull.wait(&m_mutex);
}
m_data[m_writeIndex] = data;
m_writeIndex = (m_writeIndex + 1) % BUFFER_SIZE;
m_dataCount++;
m_notEmpty.wakeAll();
}
int read()
{
QMutexLocker locker(&m_mutex);
while (m_dataCount == 0) {
m_notEmpty.wait(&m_mutex);
}
int data = m_data[m_readIndex];
m_readIndex = (m_readIndex + 1) % BUFFER_SIZE;
m_dataCount--;
m_notFull.wakeAll();
return data;
}
private:
int m_readIndex;
int m_writeIndex;
int m_dataCount;
int m_data[BUFFER_SIZE];
QMutex m_mutex;
QWaitCondition m_notEmpty;
QWaitCondition m_notFull;
};
class WriterThread : public QThread
{
public:
WriterThread(Buffer* buffer)
: m_buffer(buffer)
{
}
protected:
void run() override
{
for (int i = 0; i < 100; i++) {
m_buffer->write(i);
msleep(100);
}
}
private:
Buffer* m_buffer;
};
class ReaderThread : public QThread
{
public:
ReaderThread(Buffer* buffer)
: m_buffer(buffer)
{
}
protected:
void run() override
{
for (int i = 0; i < 100; i++) {
int data = m_buffer->read();
qDebug() << data;
msleep(50);
}
}
private:
Buffer* m_buffer;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Buffer buffer;
WriterThread writerThread(&buffer);
ReaderThread readerThread(&buffer);
writerThread.start();
readerThread.start();
return a.exec();
}
```
在上述代码中,Buffer 类是一个共享的缓冲区,其中包含一个数组和三个同步对象:QMutex、QWaitCondition m_notEmpty 和 QWaitCondition m_notFull。WriterThread 类是一个写入线程,不断向缓冲区中写入数据。ReaderThread 类是一个读取线程,从缓冲区中读取数据。在写入线程中,如果缓冲区已满,则调用 m_notFull.wait(&m_mutex) 等待,直到缓冲区不满为止。在读取线程中,如果缓冲区为空,则调用 m_notEmpty.wait(&m_mutex) 等待,直到缓冲区不空为止。在写入数据和读取数据后,分别调用 m_notEmpty.wakeAll() 和 m_notFull.wakeAll() 唤醒等待的线程。
阅读全文