[Qt-interest] QAtomicInt and QThread
Francisco Gonzalez
gzmorell at gmail.com
Fri Jun 24 10:46:44 CEST 2011
Hi,
this example compiles and run ok, but is it correct?
//code
#include <QtCore/QCoreApplication>
#include <QObject>
#include <QTimer>
#include <QThread>
#include <QAtomicInt>
#include <QDebug>
class Object :public QObject
{
Q_OBJECT
public:
Object(QObject *parent =0):QObject(parent),m_count(0),m_follow(1){}
signals:
void finished();
public slots:
void loop() {
qDebug() << "Loop Started";
while (m_follow==1)
{
m_count++;
}
qDebug() << m_count;
emit finished();
}
void reset() {
m_follow=0;
}
quint64 read() {
quint64 result = m_count;
qDebug() << result;
return result;
}
private:
quint64 m_count;
QAtomicInt m_follow;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTimer timeToStop;
QTimer timeToRead;
QThread thread;
Object object;
timeToStop.setInterval(10000);
timeToRead.setInterval(1000);
QObject::connect(&thread,SIGNAL(started()),&object,SLOT(loop()));
QObject::connect(&timeToRead,
SIGNAL(timeout()),&object,SLOT(read()), Qt::DirectConnection);
QObject::connect(&timeToStop,SIGNAL(timeout()),&object,SLOT(reset()),Qt::DirectConnection);
QObject::connect(&object,SIGNAL(finished()),&thread,SLOT(quit()));
QObject::connect(&thread,SIGNAL(finished()),&a,SLOT(quit()));
object.moveToThread(&thread);
timeToStop.start();
timeToRead.start();
thread.start();
return a.exec();
}
#include "main.moc"
// end code
More information about the Qt-interest-old
mailing list