#include <QtCore/QCoreApplication>
#include <QThread>
#include <QMetaType>
#include <QMutex>
#include <iostream>
{
using namespace std;
mutex.lock(); // if we run it without mutex, lines may be mixed
cout <<
QThread::currentThreadId() <<
" " << qPrintable
(message
) << endl;
mutex.unlock();
}
{
Q_OBJECT
public slots:
void startPrinting()
{
for (int i = 0; i < 1000; ++i)
{
// perform some processing...
// ...
// print something on the screen/to the log/whatever
}
emit finished();
}
signals:
void finished();
};
//Q_DECLARE_METATYPE(Printer*)
int main(int argc, char *argv[])
{
Printer *printer1 = new Printer;
printer1->moveToThread(t1);
Printer *printer2 = new Printer;
printer2->moveToThread(t2);
QObject::connect(t1,
SIGNAL(started
()), printer1,
SLOT(startPrinting
()));
QObject::connect(printer1,
SIGNAL(finished
()), t1,
SLOT(quit
()));
QObject::connect(t1,
SIGNAL(finished
()), printer1,
SLOT(deleteLater
()));
QObject::connect(t1,
SIGNAL(finished
()), t1,
SLOT(deleteLater
()));
QObject::connect(t2,
SIGNAL(started
()), printer2,
SLOT(startPrinting
()));
QObject::connect(printer2,
SIGNAL(finished
()), t2,
SLOT(quit
()));
QObject::connect(t2,
SIGNAL(finished
()), t2,
SLOT(deleteLater
()));
QObject::connect(t2,
SIGNAL(finished
()), printer2,
SLOT(deleteLater
()));
t1->start();
t2->start();
return a.exec();
}
#include "main.moc"
#include <QtCore/QCoreApplication>
#include <QThread>
#include <QMetaType>
#include <QMutex>
#include <iostream>
void print(const QString &message)
{
using namespace std;
static QMutex mutex;
mutex.lock(); // if we run it without mutex, lines may be mixed
cout << QThread::currentThreadId() << " " << qPrintable(message) << endl;
mutex.unlock();
}
class Printer: public QObject
{
Q_OBJECT
public slots:
void startPrinting()
{
for (int i = 0; i < 1000; ++i)
{
// perform some processing...
// ...
// print something on the screen/to the log/whatever
print(QString("i = %1").arg(i));
}
emit finished();
}
signals:
void finished();
};
//Q_DECLARE_METATYPE(Printer*)
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThread *t1 = new QThread;
Printer *printer1 = new Printer;
printer1->moveToThread(t1);
QThread *t2 = new QThread;
Printer *printer2 = new Printer;
printer2->moveToThread(t2);
QObject::connect(t1, SIGNAL(started()), printer1, SLOT(startPrinting()));
QObject::connect(printer1, SIGNAL(finished()), t1, SLOT(quit()));
QObject::connect(t1, SIGNAL(finished()), printer1, SLOT(deleteLater()));
QObject::connect(t1, SIGNAL(finished()), t1, SLOT(deleteLater()));
QObject::connect(t2, SIGNAL(started()), printer2, SLOT(startPrinting()));
QObject::connect(printer2, SIGNAL(finished()), t2, SLOT(quit()));
QObject::connect(t2, SIGNAL(finished()), t2, SLOT(deleteLater()));
QObject::connect(t2, SIGNAL(finished()), printer2, SLOT(deleteLater()));
t1->start();
t2->start();
return a.exec();
}
#include "main.moc"
To copy to clipboard, switch view to plain text mode
Bookmarks