Suppose the minimal case , which contains one class named Worker
based on QThread
, and another named Parser
, which is a global class , resided in Worker
c开发者_如何学Golass.
# parser.h
class Parser;
extern Parser *App_Parser;
class Parser {
bool init() { App_Parser = new Parser(); }
}
# parser.cpp
Parser *App_Parser = 0;
# worker.cpp
class Worker: public QThread {
Worker(int thread_id , QObject *parent) {
Parser::init ();
connect ( App_Parser , .... , this , SLOT(parseCompleted()) );
}
private slots:
void parseCompleted () {
qDebug() << "Thread ID: " << thread_id << " completed";
}
}
So here goes the problem , if i created 12
Worker in a higher class , i sometimes could see invalid thread_id
, and it's always just one above it , in this case , always 13
.
And if i don't use App_Parser , but just use new Parser()
for an simple instance , it works.
So i'm thinking about why global variables shouldn't be used here.
Read this. It makes using threads in Qt a little bit cleaner: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
Whole problem is about where does QObject lives. When you create new Worker, you create QThread in main thread, so all it's events/signals are also parsed in main thread. You misunderstood whole qt "thread thing".
精彩评论