CppCommon  1.0.4.1
C++ Common Library
threads_wait_ring.cpp

Multiple producers / multiple consumers wait ring 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 ring
// Start consumer thread
auto consumer = std::thread([&ring]()
{
int item;
do
{
// Dequeue the item or end consume
if (!ring.Dequeue(item))
break;
// 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 the item or end produce
if (!ring.Enqueue(item))
break;
if (item == 0)
{
// Close the wait ring
ring.Close();
break;
}
}
// Wait for the consumer thread
consumer.join();
return 0;
}
Multiple producers / multiple consumers wait ring.
Definition: wait_ring.h:31
bool Enqueue(const T &item)
Enqueue an item into the wait ring.
Definition: wait_ring.inl:39
bool Dequeue(T &item)
Dequeue an item from the wait ring.
Definition: wait_ring.inl:70
void Close()
Close the wait ring.
Definition: wait_ring.inl:94
Multiple producers / multiple consumers wait ring definition.