Home > Software engineering >  C input/output queue for multiple input source
C input/output queue for multiple input source

Time:09-30

I have a task that requires listening to multiple data source, and process the data to calculate some statistics (like cumulative sum of all data) for every new record coming in.

I am reading this post for a queue with condition variables. I wonder if this solution will work for multiple input scenario.

Say we have two listener thread A & B, and one consumer thread. Listener A calls the push function, gains and releases the lock, then notify the consumer with condition variable. Is it possible that Listener B will take over immediately as it has received data in the meantime, stopping the consumer from processing the new data introduced by A? How can one make sure that the consumer logic has ran exactly once whenever new data comes in, regardless of which listener it comes from?

CodePudding user response:

Yes, but what is the the problem? Producer A (we call them producers) will lock, add an item to the queue, notify, unlock (or in some versions - not in C - unlock and then notify). Producer B will lock, add an item, notify, unlock. The consumer will wake up, lock, check the queue, get an item, unlock, and process the item. Then the consumer will lock, check the queue before waiting again and it will see there is already an item there so it will not wait. It will get the item and unlock.

When using condition variables, it is important that you check if the thing you are waiting for has already happened before you wait.

  • Related