I've listened to Herb Stutter's youtube talks on lock-free data structures and I wanted to try and use a lock-free queue. I decided to use MPMCQueue.h available on github, having found numerous examples.
The reason I chose MPMCQueue.h is it looked simple enough, only having 180 lines of code.
The idea with a multi producer multi consumer lock-free queue is that multiple threads can push and pop to and from the queue without having a lock and optionally a condition variable (if a unique_lock).
The question I have is how to have multiple threads consume without spinning, Before using MPMCQueue.h I was using std::queue and using a unique_lock with a condition variable.
The producer would then wake the condition with a notify(). The benefit of a condition variable is that it sleeps while waiting, thus minimising CPU cycle usage.
Currently there are 2 threads, each in a while (true) loop. Inside the loop the unique lock with an associated condition variable verifies if the queue is indeed not empty before popping.
Something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
while(true)
{
{
std::unique_lock<std::mutex> lock(mutex_);
item _item;
cv_queue_.wait(lock, [this,&_item]{return requests_.try_pop(_item);});
}
/*
do some work
*/
}
|
So I am unsure how to have threads without a lock, on a lock-free queue.
I am confused on how to go about using a lock-free queue , which I assumed would reduce workload.