Solved Concurrency between two functions using Qtimer's
-
In my Qt application, I have created a thread to offload all the processing to it. My software design is such that, I have the following:
-
A Queue of size 1500.
-
A timer_1 that will invoke a function_1 every 1ms. This function is responsible for enqueuing a sample into the Queue. So every 1ms, a new sample is enqueued to the Queue.
-
A timer_2 that will invoke a function_2 every 600ms. So, by the time the timer_2 is triggered, the Queue would have about ~600 samples in it ready to be processed. The function_2 will process these samples and empty the Queue.
So, the function_1 and function_2 both will be accessing the Queue while running concurrently. From the above, it is evident that there needs to be some kind of synchronization between the two functions.
Questions
-
What will happen if 1ms elapses while function_2 is being executed?. Will the function_2 be interrupted and the control goes to function_1 to enqueue a new sample or does it wait for the function_2 to complete and then move to function_1?
-
What is the best way to maintain concurrency between the functions to not miss out on any samples and to make sure the Queue never becomes full or empty?
-
-
@weedy said in Concurrency between two functions using Qtimer's:
What will happen if 1ms elapses while function_2 is being executed?. Will the function_2 be interrupted and the control goes to function_1 to enqueue a new sample or does it wait for the function_2 to complete and then move to function_1?
If both function_1 and function_2 are in the same thread, then Qt signal-slot system will enqueue timer_1 calls until function_2 is done. If they are in different threads, you need to protect the queue using QMutex, for example. Or make sure your signal-slot connections are Qt::QueuedConnections.
What is the best way to maintain concurrency between the functions to not miss out on any samples and to make sure the Queue never becomes full or empty?
Best way depends on specifics of your task. Does function_2 need a lot of time to process the ~600 samples? Does it take less or more than 600 ms?
I would not bother with the queue becoming empty, to be honest. That just means your algorithm is able to meet the demand, and that is simply good :-)