Qt 4: The book

Page 349

12.4 Using Signals and Slots Between Threads

thread3.setObjectName("thread3"); thread1.start(); thread2.start(); thread3.start(); thread1.wait(); thread2.wait(); thread3.wait(); return 0; }

The debug output on the console shows that each thread in the QThreadStorage instants really does ďŹ nd a different data structure. We can see this from the different address for the respective pointer each time: "thread3" : Creating list. Pointer: 0x8051b80 "thread2" : Creating list. Pointer: 0x8052090 "thread1" : Creating list. Pointer: 0x80573f0

Even after a few seconds there are also differences in the amount of data collected: "thread2" : 4 dates collected "thread1" : 7 dates collected "thread3" : 6 dates collected

For each process, Qt allows a maximum of 256 QThreadStorage objects. In most cases this is not a problem. It is more important to know that the class automatically deletes the data for a thread as soon as this thread is ended.

12.4 Using Signals and Slots Between Threads In Qt 4 it is possible to connect signals and slots across threads. This can be done thanks to so-called queued connections, which exist in Qt 4 in addition to the traditional direct connections. By direct connections we mean connections within a thread or process, as you learned in Chapter 7. With queued connections, possible arguments of signals are copied, and these are handed over to the recipient thread on the next thread change. Usually, worker threads emit signals containing messages in the form of the arguments, which are taken up by a slot in the main thread. The reverse is also possible, but then the worker thread requires its own event loop (see Section 12.5 on page 350). We can demonstrate this principle by extending the thread variation of the TimeServer example from Chapter 12.1 (page 338) so that the worker threads emit messages that arrive in a window in the GUI thread.

347


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.