[Qt-interest] Adding signal/slot connections in a loop

Stephen Bryant steve at bawue.de
Thu Jul 14 21:54:58 CEST 2011


Hi Derek,

> I am trying to implement a producer-consumer queue system. In my producer,
> I have a loop that is generating the input data for the consumer. I plan
> on adding these input data to a queue.  My question is - how do I make the
> producer notify the consumer that the queue now has stuff in it? I was
> thinking of also creating a QFutureWatcher in the loop(on the heap? or can
> I add multiple futures to a futurewatcher)  and creating a connection
> ebtween that watcher and making the consumer the slot.
> 
> Is this the right way to go about this?

Sounds like a typical semaphore use-case to me - you don't need to go creating 
connections in a loop.

Your producer and consumer can run in separate threads and use the same 
semaphore instance (QSemaphore functions are thread safe).  The producer calls 
semaphore.release() when it's ready and the consumer waits by calling 
semaphore.acquire() [blocking] or semaphore.tryAcquire() [non-blocking].

Have a look at http://doc.qt.nokia.com/latest/qsemaphore.html - which also has 
a link to a semaphores example for a producer/consumer combo.

The example shows you how to manage an explicitly sized resource, and will 
cause the producer to wait if the consumer can't keep up.

Don't forget: just because the semaphore is thread safe, your queue may not 
be.  You might also want to use QMutex or QReadWriteLock to ensure both 
threads don't try to modify the queue at the same time.


Steve
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110714/24ba1486/attachment.bin 


More information about the Qt-interest-old mailing list