Jump to content
  • Advertisement
Sign in to follow this  
beebs1

Producer/Consumer

This topic is 2473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hiya,

I hope I've explained this clearly enough smile.png

I'm using a producer/consumer queue to pass log messages to a seperate thread, to be written to disk. The queue is a lock-free implementation, and the consumer currently spins waiting to pop() the next message from the queue.

I'd like to modify this so that the consumer can sleep until any messages come in, so I've had a look at condition variables.

I'm a little unsure how they work though - if anyone could take a look at the following, it would be a great help.


condition_variable condition;

void produce(const Message& msg)
{
messageQueue.push(msg); // assume this is thread-safe

condition.notifyOne(); // tell the consumer to wake up
}

void consume()
{
while(!bStop)
{
condition.wait(); // wait until one or more messages arrive.

// empty the queue and write each message to disk.
while(messageQueue.tryPop(...))
{
// write the message to disk.
}
}
}

void stopConsumer()
{
bStop = true;

condition.notifyOne(); // stop the consumer from waiting, so it realises it needs to stop.
}


Do notify() calls get queued on a condition variable until they are matched with a wait() ?

If not, my pseudo-implementation appears to have a race condition between the consumer thinking the queue is empty and the producer calling notifyOne().

Any information is must appreciated!

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!