[Qt-interest] Fwd: QAtomicInt and QThread
Francisco Gonzalez
gzmorell at gmail.com
Fri Jun 24 12:31:32 CEST 2011
This could be an example. Is the read thread safe? and is it need to
use a blocking method like the use of m_read?
//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),
m_read(0){}
signals:
void finished();
public slots:
void loop() {
qDebug() << "Loop Started";
while (m_follow==1)
{
while (! m_read)
m_count++;
}
qDebug() << m_count;
emit finished();
}
void reset() {
m_follow=0;
}
quint64 read() {
m_read = 1;
quint64 result = m_count;
m_read = 0;
qDebug() << result;
return result;
}
private:
quint64 m_count;
volatile int m_follow;
QAtomicInt m_read;
};
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"
// code
---------- Forwarded message ----------
From: Francisco Gonzalez <gzmorell at gmail.com>
Date: 2011/6/24
Subject: Re: [Qt-interest] QAtomicInt and QThread
To: Thiago Macieira <thiago at kde.org>
2011/6/24 Thiago Macieira <thiago at kde.org>:
> On Friday, 24 de June de 2011 10:46:44 Francisco Gonzalez wrote:
>> this example compiles and run ok, but is it correct?
>
> Maybe it is. We don't know what you're trying to do.
>
> We can't tell if it is correct or not if we don't know what it's supposed to
> do and what the conditions are. Please explain them too.
Sorry for the confusion,
I was trying to control the thread from the main thread. I see that a
simple volatile will be enough.
"volatile int m_follow" will do the job. So it is a bad example.
>
> I see some manipulation of a non-atomic 64-bit int inside a loop and reading
> of the same 64-bit integer from another function. Since you didn't try to use
> the atomic there, I don't suppose you care that this is non-atomic and can
> produce weird results.
Does the read() function lives in the same thread as the loop function
in the example?, and then, is it safe to read the m_count using the
read() slot from another thread
If not is it possible to use QAtomicInt to block the part of the code
that modifies the data?
More information about the Qt-interest-old
mailing list