-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaphore.cpp
More file actions
47 lines (37 loc) · 1.38 KB
/
Semaphore.cpp
File metadata and controls
47 lines (37 loc) · 1.38 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
/**
* The Semaphore class provides a synchronization mechanism to control access to a shared resource.
**/
#include "Semaphore.h"
Semaphore::Semaphore(int count) : count_(count) {}
void Semaphore::Wait() {
std::unique_lock<std::mutex> lock(mutex_);
// If the count is zero, add the current thread to the waiting queue and wait until signaled.
if (count_ == 0) {
waiting_queue_.push(std::this_thread::get_id());
condition_.wait(lock, [this] {
return !waiting_queue_.empty() && waiting_queue_.front() == std::this_thread::get_id();
});
}
count_--; // Decrement the count to acquire the resource.
}
void Semaphore::Signal() {
std::lock_guard<std::mutex> lock(mutex_);
count_++; // Increment the count.
// If there are threads waiting, notify one of them.
if (!waiting_queue_.empty()) {
std::thread::id id = waiting_queue_.front();
waiting_queue_.pop();
condition_.notify_all();
}
}
void Semaphore::Signal(int count) {
std::lock_guard<std::mutex> lock(mutex_);
count_ += count; // Increase the count by the specified amount.
// Notify waiting threads up to the specified count.
while (!waiting_queue_.empty() && count > 0) {
std::thread::id id = waiting_queue_.front();
waiting_queue_.pop();
condition_.notify_all();
count--;
}
}