Design a simplified, thread‑safe producer‑consumer system that consists of a fixed‑size buffer, a producer, and a consumer.
Storage)The shared buffer holds integers and exposes two non‑blocking operations:
bool insert(int value);
bool remove(int& out);
Rules:
insert(value) succeeds and returns true only when fewer items than the capacity are present; otherwise it ignores the request and immediately returns false.remove(out) succeeds and returns true only when at least one item exists; the oldest item stored is written into out. On failure it returns false.Generator)Generator(unsigned ratePerSecond, Storage& buffer);
void start();
void shutdown();
Requirements:
ratePerSecond = k means the producer tries to create k items each second.0: 0, 1, 2, ….insert fails because the buffer is full, that particular integer is discarded; the producer then generates the next integer on its subsequent attempt (it does not retry the same value).Consumer(unsigned ratePerSecond, Storage& buffer);
void start();
void shutdown();
Requirements:
ratePerSecond = k means the consumer attempts to retrieve an item k times each second.remove fails because the buffer is empty, that attempt is simply lost; the consumer resumes polling in the next period.In a driver function (e.g., execute()):
Generator thread.Consumer thread.Do not embed a fixed duration inside start(). Instead, use a thread‑safe stop indicator, for example std::atomic<bool>.
bool stop cause a data race?std::atomic<bool> use by default?memory_order_relaxed sufficient for an isolated stop flag?The first line of input supplies the buffer capacity C and the number of commands Q.
Subsequent Q lines each contain one command:
STORE x – attempts to insert x; output true or false on its own line.TAKE – attempts to remove the oldest item; output the integer on success, else false.COUNT – output the current number of items residing in the buffer.1 <= C <= 500001 <= Q <= 150000-5 000 000 000 <= item <= 5 000 000 000Input:
2 8
STORE 1
STORE 2
STORE 3
COUNT
TAKE
STORE 4
TAKE
TAKE
Output:
true
true
false
2
1
true
2
4
Input:
2 8
STORE 10
STORE 20
STORE 30
COUNT
TAKE
STORE 40
TAKE
TAKE
Output:
true
true
false
2
10
true
20
40
Explanation:
Capacity is 2. After inserting 10 and 20 the buffer is full, so inserting 30 fails. COUNT reports 2 items. The first TAKE removes 10. Inserting 40 succeeds, filling the buffer again. The next two removes retrieve 20 and then 40.
C = 2 commands = [('STORE',10), ('STORE', 20), ('STORE', 30), ('COUNT', ), ('TAKE', ), ('STORE', 40), ('TAKE', ), ('TAKE', )]
true true false 2 10 true 20 40
Input: capacity 2, empty buffer, and 8 commands to process in order.
C = 2 commands = [('STORE',10), ('STORE', 20), ('STORE', 30), ('COUNT', ), ('TAKE', ), ('STORE', 40), ('TAKE', ), ('TAKE', )]
true true false 2 10 true 20 40
Input: capacity 2, empty buffer, and 8 commands to process in order.