views:

82

answers:

1

I have a QThread derived class that communicates with the main thread by sending QEvents to it.

What is the best way for the main thread to communicate with the second thread?

The main thread has a pointer to the second one.

+3  A: 

The best way to communicate between objects in Qt is to use signals and slots. It is a thread-safe way that is handled by the event loop and requires no locking on your part. You can also use events, though that use seems a little weird - an event is a notification of something happening, not a tool to chat.

You can also use threading primitives like QMutex, QSemaphore, QWaitCondition and QReadWriteLock (same as a QMutex, but as it's name suggests, allows you to lock for either reading or writing, not both at the same time).

You should read the Qt documentation, specifically I recommend you start with the Thread Support in Qt page.

iconiK
What class would be a good choice for a thread that runs for the duration of the main thread and periodically performs network requests?
George Edison
I guess signals are perfect for that. Otherwise, a QReadWriteLock will do on a shared structure.
iconiK
@George EdisonYou can run this network requests in main thread working with QTcpSocket in asyncronious way (usng signals and slots).
VestniK
@Ves: What if the network requests are made by a third party library - is there a way to still do it without threads?
George Edison
@George Edison, take a look here: http://doc.qt.nokia.com/4.6/examples-network.html
Adam W
@Adam: Thanks. This example helped me quite a bit: http://doc.qt.nokia.com/4.6/network-blockingfortuneclient.html
George Edison