-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathts_bounded_blocking_queue.cpp
More file actions
92 lines (78 loc) · 2.28 KB
/
ts_bounded_blocking_queue.cpp
File metadata and controls
92 lines (78 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <mutex>
#include <optional>
#include <thread>
using namespace std;
/*
Problem:
Implement a thread-safe bounded blocking queue for a producer-consumer system.
Requirements:
1. Multiple producers and multiple consumers must be supported.
2. Producers block when the queue is full.
3. Consumers block when the queue is empty.
4. Add a graceful shutdown so waiting threads can exit cleanly.
5. Keep the implementation and demo in a single file.
Follow-ups to practice:
- Add timed push/pop APIs.
- Add metrics (drops, waits, throughput).
- Make the queue generic and move-only friendly.
*/
template <typename T>
class BoundedBlockingQueue {
deque<T> buffer;
size_t capacity;
bool closed = false;
mutex mtx;
condition_variable not_empty;
condition_variable not_full;
public:
explicit BoundedBlockingQueue(size_t cap) : capacity(cap) {}
bool push(T value) {
(void)value;
// TODO:
// 1. Wait until queue has space or shutdown is triggered.
// 2. Return false if queue is closed.
// 3. Push value, then notify one consumer.
return false;
}
optional<T> pop() {
// TODO:
// 1. Wait until queue has an item or shutdown is triggered.
// 2. If queue is empty and closed, return nullopt.
// 3. Pop item, notify one producer, return item.
return nullopt;
}
void shutdown() {
// TODO:
// 1. Mark queue as closed under lock.
// 2. Wake all waiting producers and consumers.
}
size_t size() {
// TODO:
// Return current queue size under lock.
return 0;
}
};
void producer(BoundedBlockingQueue<int>& q, int producer_id, int start_value) {
(void)q;
(void)producer_id;
(void)start_value;
// TODO:
// Produce a sequence of values and push into queue.
}
void consumer(BoundedBlockingQueue<int>& q, int consumer_id) {
(void)q;
(void)consumer_id;
// TODO:
// Repeatedly pop until shutdown/empty sentinel behavior is defined.
}
int main() {
// TODO:
// 1. Construct queue with a small capacity.
// 2. Start multiple producer/consumer threads.
// 3. Join producers, then call shutdown().
// 4. Join consumers.
return 0;
}