CppCommon  1.0.4.1
C++ Common Library
threads_mpmc_ring_queue.cpp

Multiple producers / multiple consumers wait-free ring queue example

#include <iostream>
#include <string>
#include <thread>
int main(int argc, char** argv)
{
std::cout << "Please enter some integer numbers. Enter '0' to exit..." << std::endl;
// Create multiple producers / multiple consumers wait-free ring queue
// Start consumer thread
auto consumer = std::thread([&queue]()
{
int item;
do
{
// Dequeue using yield waiting strategy
while (!queue.Dequeue(item))
std::this_thread::yield();
// Consume the item
std::cout << "Your entered number: " << item << std::endl;
} while (item != 0);
});
// Perform text input
std::string line;
while (getline(std::cin, line))
{
int item = std::stoi(line);
// Enqueue using yield waiting strategy
while (!queue.Enqueue(item))
std::this_thread::yield();
if (item == 0)
break;
}
// Wait for the consumer thread
consumer.join();
return 0;
}
Multiple producers / multiple consumers wait-free ring queue.
bool Enqueue(const T &item)
Enqueue an item into the ring queue (multiple producers threads method)
bool Dequeue(T &item)
Dequeue an item from the ring queue (multiple consumers threads method)
Multiple producers / multiple consumers wait-free ring queue definition.