为什么不能在基于 QThread 的类中使用全局变量?
假设最小情况,其中包含一个基于 QThread
的名为 Worker
的类,以及另一个名为 Parser
的全局类,位于 <代码>Worker 类。
# 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";
}
}
所以问题就来了,如果我在更高的类中创建了12
Worker,我有时会看到无效的thread_id
,并且它总是只有上面的一个,在这种情况下,总是13
。
如果我不使用 App_Parser ,而只是使用 new Parser()
作为一个简单的实例,它就可以工作。
所以我在想为什么这里不应该使用全局变量。
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
class.
# 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
读一下这个。它使得在 Qt 中使用线程更加清晰: http ://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
整个问题在于 QObject 存在于哪里。当您创建新的 Worker 时,您会在主线程中创建 QThread,因此它的所有事件/信号也会在主线程中解析。你误解了整个qt“线程的事情”。
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".