Signal and Slot Two Threads
-
I have a Problem. I am using 2 Threads, so that my GUI cannot lock up.
I start both threads and htop is showing me two threads.
For now, I force my working thread to enter an infinite loop once a slot is triggered.
In my GUI Thread I emit the corresponding signal, but the whole program locks up.
I have connected the two threads like this.
@ connect(this, SIGNAL(setswitch(QString,int)), this->thread2, SLOT(setswitch(QString, int)), Qt::QueuedConnection);
@When I change the signal and slot from QString to char* the main thread stays alive, just like expected.
When I printed the char* in the working thread before entering the infinite loop, it only shows bogus.What did I miss? Why can I not connect between the two threads using the QString.
-
could you provide more code? how do you create those threads?
maybe http://doc.qt.nokia.com/master-snapshot/thread-basics.html helps, there are some well explained examples.
-
-
The thread_class is the object that I send to the infinite loop.
@class thread_class : public QThread
{
Q_OBJECT
public:
thread_class();
void run();public slots:
void setswitch(QString board, int num);signals:
private:
};@The slot is implemented like this.
@void thread_class::setswitch(QString board, int num){
std::cout << qPrintable(board) << std::endl;
while(1);
}@I just create this thread inside another class.
-
You are doing it wrong (TM)
See the excellent "article":http://developer.qt.nokia.com/wiki/Threads_Events_QObjects on the Wiki on how to deal with Threads, objects, signals & slots and events.
-
Oh ok, thanks. I see that its not working since this and this->thread are Objects in the same thread.
So I have changed it like this.@class Worker : public QObject
{
Q_OBJECTpublic slots:
void doWork() {
/* ... */
}
};/* ... */
QThread thread;
Worker worker;
connect(obj, SIGNAL(workReady()), &worker, SLOT(doWork()));
worker.moveToThread(&thread);
thread.start();@So I have my class that does the work and I move this instance to the second thread. Now the Objects are no longer in the same thread and the QueuedConnection works.
Thank you.
-
Indeed. You have to remember that QThread is not a thread, it only manages one.
QThread can be subclassed (and it can make sense to do so), but you have to remember that only that what happens in the run() method actually happens in the other thread. Everything else happens in the thread that your QThread itself lives in. New signals and slots should be about the management of the thread, not about the actual work it is supposed to do.