How to properly synchronize two threads accessing a QQueue simultaneously
Hello,
in my software design I need two threads to access a queue simultaneously. One of them pushes items at the end of the queue and the other one pop items from the same queue. I declared the queue as global. I have a rough idea of how to synchronize two threads accessing the same resource using QMutex but in this case the thread that feeds the queue does it practically almost continuously so how to find a timeslot for the second thread so that it can extract items from the queue.
Can I have a help with the logic?
Thanx
Re: How to properly synchronize two threads accessing a QQueue simultaneously
Quote:
so how to find a timeslot for the second thread so that it can extract items from the queue.
You don't have to "find a timeslot". Isolate the code that reads and writes from the queue into two separate methods and protect each of those methods internally with a QMutexLocker wrapping your QMutex instance (which should be a member of the same class as the access methods. The queue doesn't have to be global. It could be a member variable of the same class that holds the mutex and read / write methods for the queue. Give each thread a pointer to this manager class and they will call the read / write methods through that.
The mutex and the OS will take care of granting access for each thread. If you find that the read thread isn't able to keep up with the write thread because the write thread is dominating access to the queue, then maybe consider giving the read thread a higher priority so it gets to run more frequently.