PDA

View Full Version : How come this slot doesn't get called every second?



ShaChris23
5th November 2009, 18:39
Why is it that, for the code below, the Thread1.printEvent() gets printed as often as Thread2.printEvent()? My thought is that since it's 2 separate event loops (due to 2 threads), Thread1.printEvent() should keep on going even though Thread2.printEvent() takes a long time?

Here's how everything is connected:

--> denotes is connected to

Thread1.timer.timeout() --> Thread1.doSomething(); // times out every 1 second
Thread1.doSomething() --> Thread1.printEvent(); // takes "zero" time
Thread1.doSomething() --> Thread2.printEvent(); // takes 10 seconds


This is the code for Thread1


#include <QThread>
#include <QTimer>

class Thread1 : public QThread
{
Q_OBJECT

public:
void run();

private:
QTimer* timer;

signals:
void doSomething();

private slots:
void printEvent();

private:
int number;
};

#include <iostream>

void Thread1::run()
{
number = 0;

// We create QTimer here because it has thread-affinity
timer = new QTimer();
if(!QObject::connect( timer,
SIGNAL(timeout()),
this,
SIGNAL(doSomething())))
{
throw std::runtime_error( "ERROR!" );
}
if(!QObject::connect( this,
SIGNAL(doSomething()),
this,
SLOT(printEvent())))
{
throw std::runtime_error( "ERROR!" );
}

timer->start(1000);
this->exec();

delete timer;
}

void Thread1::printEvent()
{
std::cout << "Thread1: sending event... " << number++ << std::endl;
}


This is the code for Thread2..


#include <QThread>

class Thread2 : public QThread
{
Q_OBJECT

public:
void run();

public slots:
void printEvent();

private:
int number;
};

#include <iostream>

void Thread2::run()
{
number = 0;
exec();
}

void Thread2::printEvent()
{
std::cout << "Thread2: Received event... " << number++ << std::endl;
if( number < 3 )
{
msleep(10000);
}
}


Lastly, this is the code for main.cpp


#include <QObject>
#include <QtCore/QCoreApplication>

int main( int argc,
char* argv[] )
{
QCoreApplication a( argc,
argv );

Thread1 thread1;
Thread2 thread2;

// Connect the 2 threads signal slot here
if (!QObject::connect(&thread1, SIGNAL(doSomething()),
&thread2, SLOT(printEvent())))
{
throw std::runtime_error( "ERROR!" );
}

thread1.start();
thread2.start();

return a.exec();
}

caduel
5th November 2009, 19:57
read up on that 5th argument to the connect call.... (and use the queued connction)

ShaChris23
6th November 2009, 00:41
@caduel:

Thanks for your suggestion. I will look into that 5th argument.