C Multithreading – Using Timers with Threads on Queue

cmultithreadingtime

So I've been asking the wrong questions for the last three days and after searching a lot I think I have an idea of what I need, my question is how to use timers with two threads writing and reading on one queue.
In other words, I have one queue(or any other data structure) and two threads, producer and consumer,
so the producer write values on the queue, with a time for each value(let's say 10 seconds) and the consumer read the queue, both are using lock mechanism, what I need is a timer function that check which value has passed the 10 seconds and remove it from the queue.

I know how to implement the producer/consumer threads, but I don't know where to put this, is it a third thread or what? and do I need to write the time of the value when entered the queue, so the timer function can check it, or just write 10 and the timer function will decrement 1 each second?

Best Answer

First, the structure you want in this case is probably a priority queue. You'll use the expiration time of each item to determine its priority in the queue.

In this case, the consumer thread waits for one of two things to happen: the time of the first item in the queue to come due, or a newly-inserted item ends up at the beginning of the queue.

Related Topic