• 4280阅读
  • 0回复

[共享]使用QThread需要注意的问题 [复制链接]

上一主题 下一主题
离线foxyz
 

只看楼主 倒序阅读 楼主  发表于: 2012-03-20
  • The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object (this) as the parent of an object created in the thread (since the QThread object itself was created in another thread).
  • Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.
  • You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.

上边一段非常重要。
1、继承QObject的对象必须在它的父对象(不是父类)同一个线程中创建。这还隐含着另外一层意思:不要在线程类中用new在heap中创建对象的时候,传入该线程作为被创建对象的parent,例如:
  1. MyThread::run() {
  2.     MyObject *obj = new MyObject(this);
  3.    ......
  4. }
2.事件驱动的类对象只能在单个线程中使用。你不能在一个线程中创建了QTimer,在另外一个线程中启动
3.所有被创建在线程中的对象必须在线程销毁前被销毁


快速回复
限100 字节
 
上一个 下一个