2

I'm using Boost's lockfree queue for a producer-consumer queue. I'd like each consumer thread to block when the queue is empty, waking up either when there's more data in the queue, or any producer terminates. But Boost doesn't seem to offer a blocking pop, only an immediate returning pop.

How should consumers wait until data is available?

SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • 1
    you can wrap boost::circular_buffer, like this http://www.boost.org/doc/libs/1_48_0/libs/circular_buffer/test/bounded_buffer_comparison.cpp – Argun Nov 20 '15 at 07:17

1 Answers1

3

You're looking to do an interesting operation: you're looking to do a blocking operation on a lockfree queue, which is kinda the opposite of what you have a lockfree queue for.

Use a normal blocking queue using a mutex and a condition variable. It's easy, and its a more standard way to do it.

You actually pay a performance penalty for lockfree in many cases, because you're guaranteeing that the queue does not hold any locks, even in the worst cases.

This question covers many of the pros and cons of both approaches.

Community
  • 1
  • 1
Cort Ammon
  • 10,221
  • 31
  • 45
  • Can you elaborate? 1. What blocking queue implementation do you recommend? 2. I'm concerned about race conditions rolling my own mutex and condition variable - what type of scheme do you recommend? what assurances are there that it's fully correct? – SRobertJames Apr 12 '15 at 05:35
  • Any implementation works fine. mutex/cond variable producer-consumer queues are standard fare for introductions to multithreading, so they don't provide too many oppertunities to run into trouble. As for race cases, just rember to always lock the mutex before doing anything. Honestly, if you are concerned with the implementation of such a locking queue, I would recommend doing it as an exercise, if nothing else. Its a good small project to practice how to think in multithreaded terms. Lockfree stuff can get you in trouble in a hurry if you haven't learned to do it with locking first. – Cort Ammon Apr 12 '15 at 05:54