A thread-safe queue with a fixed capacity that supports blocking operations.
More...
|
| | BoundedBlockingQueue (size_t capacity) |
| | Constructs a new BoundedBlockingQueue.
|
| |
| void | shut_down () |
| | Shuts down the queue and wakes up all blocked threads.
|
| |
| bool | push (int val) |
| | Adds an element to the back of the queue.
|
| |
| bool | pop (int &output_val) |
| | Removes an element from the front of the queue.
|
| |
A thread-safe queue with a fixed capacity that supports blocking operations.
- This class ensures that:
- Producers block when the queue is full.
- Consumers block when the queue is empty.
- All threads can be gracefully shut down.
Definition at line 23 of file BoundedBlockingQueue.cpp.
◆ BoundedBlockingQueue()
| BoundedBlockingQueue::BoundedBlockingQueue |
( |
size_t |
capacity | ) |
|
|
inline |
◆ pop()
| bool BoundedBlockingQueue::pop |
( |
int & |
output_val | ) |
|
|
inline |
Removes an element from the front of the queue.
- Parameters
-
| [out] | output_val | Reference where the consumed value will be stored. |
- Returns
- true if an item was successfully consumed.
-
false if the queue is empty and shut down.
Definition at line 82 of file BoundedBlockingQueue.cpp.
82 {
83 std::unique_lock<std::mutex> lock(mtx);
84
85
86 while(buffer.empty() && !is_shutdown) {
87 not_empty.wait(lock);
88 }
89
90
91 if(buffer.empty() && is_shutdown) return false;
92
93 output_val = buffer.front();
94 buffer.pop();
95 std::cout << "[Consumer] : Consumed " << output_val << " | Size : " << buffer.size() << std::endl;
96
97 not_full.notify_one();
98 return true;
99 }
Referenced by consumerTask().
◆ push()
| bool BoundedBlockingQueue::push |
( |
int |
val | ) |
|
|
inline |
Adds an element to the back of the queue.
- Parameters
-
- Returns
- true if the item was successfully pushed.
-
false if the queue was shut down before or during the push.
Definition at line 59 of file BoundedBlockingQueue.cpp.
59 {
60 std::unique_lock<std::mutex> lock(mtx);
61
62
63 while(buffer.size() >= max_capacity && !is_shutdown) {
64 not_full.wait(lock);
65 }
66
67 if(is_shutdown) return false;
68
69 buffer.push(val);
70 std::cout << "[Producer] Pushed : " << val << " | Size: " << buffer.size() << std::endl;
71
72 not_empty.notify_one();
73 return true;
74 }
Referenced by producerTask().
◆ shut_down()
| void BoundedBlockingQueue::shut_down |
( |
| ) |
|
|
inline |
Shuts down the queue and wakes up all blocked threads.
- Sets the shutdown flag and notifies all waiting producers and consumers to prevent deadlocks during program termination.
Definition at line 46 of file BoundedBlockingQueue.cpp.
46 {
47 is_shutdown = true;
48 not_full.notify_all();
49 not_empty.notify_all();
50 return;
51 }
Referenced by consumerTask(), and producerTask().
The documentation for this class was generated from the following file: