Smasho
Smasho

Reputation: 1180

Thread safe QQueue

In a Qt application, I need to add items from one thread, and consume them from another. As Qt docs state about container classes:

... they are thread-safe in situations where they are used as read-only containers by all threads used to access them.

I assume I need to create a thread safe version, or protect it with a mutex. Is there any recommended solution? Like using directly the Qt event loop, or any thread-safe class I'm missing?

Upvotes: 1

Views: 8027

Answers (1)

baci
baci

Reputation: 2588

For a queue, yes you need a thread safe version. I recommend QMutex together with QMutexLocker as it handles the unlock automatically.

If your consumer and producer work on different parts of the buffer, I recommend a semaphore instead.

Semaphores make it possible to have a higher level of concurrency than mutexes. If accesses to the buffer were guarded by a QMutex, the consumer thread couldn't access the buffer at the same time as the producer thread. Yet, there is no harm in having both threads working on different parts of the buffer at the same time.

Upvotes: 4

Related Questions