Threads and QObjects

Threads and QObjects

QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

More interesting is that QObjects can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that "live" in other threads. This is possible because each thread is allowed to have its own event loop.

QObject Reentrancy

QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket, QFtp, andQProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work. There are three constraints to be aware of:

QTimer, QTcpSocket, QUdpSocket, QFtp, andQProcess,被设计成在single thread 中创建和使用。在一个线程中创建对象,从另一个线程用调用这个对象的方法不能保证正常工作。

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

The child of a QObject 要在parent的线程中创建。

Event driven objects may only be used in a single thread。特别的,这包括timer和network模块。比如:你不能在不是object's thread中start一个timer和connect一个socket。

你要保证delete QThread之前 先delete掉thread中的objects 。可以在run()的stack上创建objects来保证这点。

 

Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread.

In practice, the impossibility of using GUI classes in other threads than the main thread can easily be worked around by putting time-consuming operations in a separate worker thread and displaying the results on screen in the main thread when the worker thread is finished. This is the approach used for implementing the Mandelbrot and the Blocking Fortune Client example.

Per-Thread Event Loop

Each thread can have its own event loop. The initial thread starts its event loops using QCoreApplication::exec(); other threads can start an event loop using QThread::exec(). Like QCoreApplication, QThread provides an exit(int) function and a quit() slot.

An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such asQTimer, QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread. This is explained in more detail in the Signals and Slots Across Threads section below.

Threads, objects, and event loops

A QObject instance is said to live in the thread in which it is created. Events to that object are dispatched by that thread's event loop. The thread in which a QObject lives is available using QObject::thread().

Note that for QObjects that are created before QApplication, QObject::thread() returns zero. This means that the main thread will only handle posted events for these objects; other event processing is not done at all for objects with no thread. Use the QObject::moveToThread() function to change the thread affinity for an object and its children (the object cannot be moved if it has a parent).

QApplication之前创建的对象QObject::thread() 是zero。这表示main thread 只会处理posted events,其他事件处理不会进行。

Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use QObject::deleteLater() instead, and a DeferredDelete event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that owns a QObject is the thread that creates theQObject, but not after QObject::moveToThread() has been called.

拥有QObject的thread是QObject创建时所在的thread,但在QObject::moveToThread() 可以改变。

If no event loop is running, events won't be delivered to the object. For example, if you create a QTimer object in a thread but never call exec(), theQTimer will never emit its timeout() signal. Calling deleteLater() won't work either. (These restrictions apply to the main thread as well.)

You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent(). The events will automatically be dispatched by the event loop of the thread where the object was created.

Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, QCoreApplication::sendEvent() (unlike postEvent()) can only be used to dispatch events to objects living in the thread from which the function is called.

Accessing QObject Subclasses from Other Threads

QObject and all of its subclasses are not thread-safe. This includes the entire event delivery system. It is important to keep in mind that the event loop may be delivering events to your QObject subclass while you are accessing the object from another thread.

If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior.

Like other objects, QThread objects live in the thread where the object was created -- not in the thread that is created when QThread::run() is called. It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex.

QThread中的slots不提倡,要注意加锁。因为QThread自身living在另一个线程。

On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.

run()可以emit signals是安全的,因为信号是thread-safe.

Signals and Slots Across Threads

Qt supports these signal-slot connection types:

  • Auto Connection (default) If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection."
  • Direct Connection The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.
  • Queued Connection The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
  • Blocking Queued Connection The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns. Note: Using this type to connect objects in the same thread will cause deadlock.
  • Unique Connection The behavior is the same as the Auto Connection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection is not made and connect() returns false.

Auto Connection:如果signal emit线程和receiving object 的线程一样。就是Direct Connection。否则是Queued Connection。

The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.

QObject::connect() itself is thread-safe.

The Mandelbrot example uses a queued connection to communicate between a worker thread and the main thread. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), all the Mandelbrot fractal computation is done in a separate worker thread. The thread emits a signal when it is done rendering the fractal.

Similarly, the Blocking Fortune Client example uses a separate thread for communicating with a TCP server asynchronously.

 

 

Thread Support in Qt 4

Qt 4 makes it easier than ever to write multithreaded applications. More classes have been made usable from non-GUI threads, and the signals and slots mechanism can now be used to communicate between threads.

General Overview

QThread now inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

Each thread can now have its own event loop. The initial thread starts its event loops using QCoreApplication::exec(); other threads can start an event loop usingQThread::exec(). Like QCoreApplication, QThread also provides an exit(int) function and a quit() slot.

 

An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as QTimer,QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread. When a signal is emitted, the slot isn't called immediately; instead, it is invoked when control returns to the event loop of the thread to which the object belongs. The slot is executed in the thread where the receiver object lives. See QObject::connect() for details.

QTimer,QTcpSocket, and QProcess需要event loop,(socket和qprocess提供了一些同步的方法,不需要event loop,但不提倡使用,因为会阻塞gui 线程)。

线程中的event loop也使得跨线程的信号槽成为可能。但信号发射时,槽不是立即调用,而是当控制权返回到接收者的thread的event loop时调用。槽在接收者所在的线程运行。

posted on 2012-06-26 16:03  katago  阅读(680)  评论(0编辑  收藏  举报