2022-05-10 10:06:48 +00:00
|
|
|
// Copyright (C) 2016 The Qt Company Ltd.
|
|
|
|
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
2011-04-27 10:05:43 +00:00
|
|
|
|
2013-10-08 10:14:20 +00:00
|
|
|
#include <QtCore>
|
2011-04-27 10:05:43 +00:00
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
//! [0]
|
|
|
|
const int DataSize = 100000;
|
2011-04-27 17:16:41 +00:00
|
|
|
|
2011-04-27 10:05:43 +00:00
|
|
|
const int BufferSize = 8192;
|
|
|
|
char buffer[BufferSize];
|
|
|
|
|
|
|
|
QWaitCondition bufferNotEmpty;
|
|
|
|
QWaitCondition bufferNotFull;
|
|
|
|
QMutex mutex;
|
|
|
|
int numUsedBytes = 0;
|
|
|
|
//! [0]
|
|
|
|
|
|
|
|
//! [1]
|
|
|
|
class Producer : public QThread
|
|
|
|
//! [1] //! [2]
|
|
|
|
{
|
|
|
|
public:
|
2011-04-27 17:16:41 +00:00
|
|
|
Producer(QObject *parent = NULL) : QThread(parent)
|
|
|
|
{
|
|
|
|
}
|
2011-04-27 10:05:43 +00:00
|
|
|
|
2016-06-15 08:12:35 +00:00
|
|
|
void run() override
|
2011-04-27 17:16:41 +00:00
|
|
|
{
|
|
|
|
for (int i = 0; i < DataSize; ++i) {
|
|
|
|
mutex.lock();
|
|
|
|
if (numUsedBytes == BufferSize)
|
|
|
|
bufferNotFull.wait(&mutex);
|
|
|
|
mutex.unlock();
|
|
|
|
|
2017-04-14 04:13:52 +00:00
|
|
|
buffer[i % BufferSize] = "ACGT"[QRandomGenerator::global()->bounded(4)];
|
2011-04-27 17:16:41 +00:00
|
|
|
|
|
|
|
mutex.lock();
|
|
|
|
++numUsedBytes;
|
|
|
|
bufferNotEmpty.wakeAll();
|
|
|
|
mutex.unlock();
|
|
|
|
}
|
2011-04-27 10:05:43 +00:00
|
|
|
}
|
2011-04-27 17:16:41 +00:00
|
|
|
};
|
2011-04-27 10:05:43 +00:00
|
|
|
//! [2]
|
|
|
|
|
|
|
|
//! [3]
|
|
|
|
class Consumer : public QThread
|
|
|
|
//! [3] //! [4]
|
|
|
|
{
|
2011-04-27 17:16:41 +00:00
|
|
|
Q_OBJECT
|
2011-04-27 10:05:43 +00:00
|
|
|
public:
|
2011-04-27 17:16:41 +00:00
|
|
|
Consumer(QObject *parent = NULL) : QThread(parent)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2016-06-15 08:12:35 +00:00
|
|
|
void run() override
|
2011-04-27 17:16:41 +00:00
|
|
|
{
|
|
|
|
for (int i = 0; i < DataSize; ++i) {
|
|
|
|
mutex.lock();
|
|
|
|
if (numUsedBytes == 0)
|
|
|
|
bufferNotEmpty.wait(&mutex);
|
|
|
|
mutex.unlock();
|
|
|
|
|
|
|
|
fprintf(stderr, "%c", buffer[i % BufferSize]);
|
|
|
|
|
|
|
|
mutex.lock();
|
|
|
|
--numUsedBytes;
|
|
|
|
bufferNotFull.wakeAll();
|
|
|
|
mutex.unlock();
|
|
|
|
}
|
|
|
|
fprintf(stderr, "\n");
|
|
|
|
}
|
|
|
|
|
|
|
|
signals:
|
|
|
|
void stringConsumed(const QString &text);
|
2011-04-27 10:05:43 +00:00
|
|
|
};
|
2011-04-27 17:16:41 +00:00
|
|
|
//! [4]
|
2011-04-27 10:05:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
//! [5]
|
|
|
|
int main(int argc, char *argv[])
|
|
|
|
//! [5] //! [6]
|
|
|
|
{
|
|
|
|
QCoreApplication app(argc, argv);
|
|
|
|
Producer producer;
|
|
|
|
Consumer consumer;
|
|
|
|
producer.start();
|
|
|
|
consumer.start();
|
|
|
|
producer.wait();
|
|
|
|
consumer.wait();
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
//! [6]
|
2011-04-27 17:16:41 +00:00
|
|
|
|
|
|
|
#include "waitconditions.moc"
|