CppCommon  1.0.4.1
C++ Common Library
threads_wait_batcher.cpp

Multiple producers / multiple consumers wait batcher example

#include <iostream>
#include <iterator>
#include <string>
#include <thread>
int main(int argc, char** argv)
{
std::cout << "Please enter some string. Enter the empty string to exit..." << std::endl;
// Create multiple producers / multiple consumers wait batcher
// Start consumer thread
auto consumer = std::thread([&batcher]()
{
std::vector<char> items;
// Dequeue items until the batcher is closed
while (batcher.Dequeue(items))
{
std::cout << "Your entered: ";
std::copy(items.begin(), items.end(), std::ostream_iterator<char>(std::cout, ""));
std::cout << std::endl;
}
});
// Perform text input
std::string line;
while (getline(std::cin, line))
{
// Enqueue the item or end produce
if (!batcher.Enqueue(line.begin(), line.end()))
break;
if (line.empty())
{
// Close the wait batcher
batcher.Close();
break;
}
}
// Wait for the consumer thread
consumer.join();
return 0;
}
Multiple producers / multiple consumers wait batcher.
Definition: wait_batcher.h:32
void Close()
Close the wait batcher.
bool Dequeue(std::vector< T > &items)
Dequeue all items from the wait batcher.
bool Enqueue(const T &item)
Enqueue an item into the wait batcher.
Multiple producers / multiple consumers wait batcher definition.