MCPcopy Create free account
hub / github.com/Tracktion/choc / demonstrateSingleReaderMultipleWriterFIFO

Function demonstrateSingleReaderMultipleWriterFIFO

examples/threading_patterns.cpp:232–303  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

230}
231
232void demonstrateSingleReaderMultipleWriterFIFO()
233{
234 std::cout << "\n=== SingleReaderMultipleWriterFIFO Demo ===\n";
235
236 choc::fifo::SingleReaderMultipleWriterFIFO<Task> fifo;
237 fifo.reset (20); // 20 item capacity
238
239 std::atomic<bool> shouldStop{false};
240 std::atomic<int> tasksProduced{0};
241 std::atomic<int> tasksConsumed{0};
242
243 // Multiple producer threads
244 std::vector<std::thread> producers;
245
246 for (int producerId = 0; producerId < 3; ++producerId)
247 {
248 producers.emplace_back ([&, producerId]()
249 {
250 int taskID = 0;
251
252 while (! shouldStop.load())
253 {
254 ++taskID;
255
256 Task task (producerId * 1000 + taskID,
257 "Producer " + std::to_string (producerId) + " task " + std::to_string (taskID));
258
259 if (fifo.push (task))
260 {
261 tasksProduced.fetch_add (1);
262 std::cout << "Producer " << producerId << " produced task " << task.id << "\n";
263 }
264 else
265 {
266 std::cout << "FIFO full, producer " << producerId << " couldn't produce task " << task.id << "\n";
267 }
268
269 std::this_thread::sleep_for (std::chrono::milliseconds (200 + producerId * 50));
270 }
271 });
272 }
273
274 // Single consumer thread
275 std::thread consumer ([&]()
276 {
277 Task task;
278 while (! shouldStop.load() || fifo.getUsedSlots() > 0)
279 {
280 if (fifo.pop (task))
281 {
282 tasksConsumed.fetch_add (1);
283 auto now = std::chrono::steady_clock::now();
284 auto latency = std::chrono::duration_cast<std::chrono::milliseconds>(now - task.timestamp);
285 std::cout << "Consumed task " << task.id << " (" << task.description << ") - latency: " << latency.count() << "ms\n";
286 }
287
288 std::this_thread::sleep_for (std::chrono::milliseconds (100));
289 }

Callers 1

mainFunction · 0.85

Calls 6

emplace_backMethod · 0.80
loadMethod · 0.80
resetMethod · 0.45
pushMethod · 0.45
getUsedSlotsMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected