#include <QtCore>
#include <QDebug>
Q_OBJECT
public:
: QObject(p
), m_num
(number
), m_lock
(lock
) {
}
public slots:
void process() {
qDebug
() <<
QString("Thread %1 started").
arg(m_num
);
for (int i = 0; i < 10; ++i) {
sleep(1);
qDebug
() <<
QString("Thread %1 reading").
arg(m_num
);
}
qDebug
() <<
QString("Thread %1 done").
arg(m_num
);
emit finished();
}
signals:
void finished();
private:
int m_num;
};
int main(int argc, char **argv) {
for (int i= 0; i < 3; ++i) {
SlowReader *worker = new SlowReader(i, &lock);
worker->moveToThread(thread);
QObject::connect(thread,
SIGNAL(started
()), worker,
SLOT(process
()));
QObject::connect(worker,
SIGNAL(finished
()), thread,
SLOT(quit
()));
QObject::connect(worker,
SIGNAL(finished
()), worker,
SLOT(deleteLater
()));
QObject::connect(thread,
SIGNAL(finished
()), thread,
SLOT(deleteLater
()));
thread->start();
}
return app.exec();
}
#include "main.moc"
#include <QtCore>
#include <QDebug>
class SlowReader: public QObject {
Q_OBJECT
public:
SlowReader(int number, QReadWriteLock *lock, QObject *p = 0)
: QObject(p), m_num(number), m_lock(lock)
{
}
public slots:
void process() {
QReadLocker locker(m_lock);
qDebug() << QString("Thread %1 started").arg(m_num);
for (int i = 0; i < 10; ++i) {
sleep(1);
qDebug() << QString("Thread %1 reading").arg(m_num);
}
qDebug() << QString("Thread %1 done").arg(m_num);
emit finished();
}
signals:
void finished();
private:
int m_num;
QReadWriteLock *m_lock;
};
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QReadWriteLock lock;
for (int i= 0; i < 3; ++i) {
QThread* thread = new QThread;
SlowReader *worker = new SlowReader(i, &lock);
worker->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), worker, SLOT(process()));
QObject::connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
QObject::connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
return app.exec();
}
#include "main.moc"
To copy to clipboard, switch view to plain text mode
Each thread holds a read lock for the entire 10 seconds it takes to do the 10 reads.
Bookmarks