PDA

View Full Version : need help on inter Qthread communication



Ratheendrans
11th October 2010, 15:01
Hi All,

I am trying out a inter thread communication for my project.

I have copied the below example with my modification.

http://stackoverflow.com/questions/638251/how-to-emit-cross-thread-signal-in-qt

class MyObject : public QObject
{
Q_OBJECT
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
}
};
- Thread 1
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 1 started" << std::endl;
int i = 0;
while(1)
{
msleep( 200 );
i++;
if(i==1000)
emit MySignal();
}
}
signals:
void MySignal( void );
};

- MyServer is class I added
class MyServer
{

public slots :

void sendMessage(int val);


}

Thead-2
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
MyServer objServer; --This is my class instance
std::cout << "thread 2 started" << std::endl;
exec();
}
};


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CThread1 oThread1;
CThread2 oThread2;
MyObject myObject;
QObject::connect( & oThread1, SIGNAL( MySignal() ), &myObject, SLOT( MySlot() ) );
oThread2.start();
myObject.moveToThread(&oThread2)
oThread1.start();
return a.exec();
}

my doubt is how we can "sendMessage" method of MyServer from "myObject's" method "MySlot:

tbscope
11th October 2010, 15:30
Just do the same with MyServer as you do with MyObject. Do not create them in the thread itself, but in, for example, the initialisation of you main window. And then move it to the correct thread. This means you can just use connect(myServer, SIGNAL(), myObject, SLOT)

Try to leave the run() function of a QThread subclass as is, or at least make sure you use exec().
What needs to be run in the thread should be added to the object you move to the thread.

Ratheendrans
12th October 2010, 05:39
Thanks for the reply.

I am able to get the expected behaviour.