http://blog.csdn.net/dbzhang800/article/details/6557272

QObject Reentrancy

  • 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 QThreadobject 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.

注意,本文试图通过源码解释下面的问题:

  • 子QObject必须在其parent关联的线程内创建
  • 调用moveToThread()的对象其parent必须为0
  • 事件驱动的对象要在单一线程内使用
    • QTimer、network模块的QTcpSocket等等
    • 为什么不能在非关联线程内开启QTimer或者连接QTcpSocket到服务器?
  • 删除QThread对象前,确保线程内所有对象都没销毁
  • AutoConnection的是是非非,两种说法孰是孰非?

    • 其一:信号关联的线程和槽关联的线程不一致时,则Queued方式
    • 其二:信号发射时的当前线程和槽函数关联的线程不一致时,则Queued方式

但很显然,我没做到这一点(能力所限,现阶段我只能让自己勉强明白),尽管如此,本文应该还是提供了很多你理解这些问题所需的背景知识。

什么东西?

每一个QObject都会和一个线程相关联

QObject 是线程感知的,每一个QObject及派生类的对象被创建时都会将其所在线程的引用保存下来(可以通过QObject::thread()返回)。

干嘛用的?

用于事件系统

QObject对象的事件处理函数始终要在其所关联线程的上下文中执行。

可否改变?

 

使用QObject::moveToThread()可以将QObject对象从一个线程移动到另一个线程。

相关文章: