Skip to content

Instantly share code, notes, and snippets.

@aerodame
Created February 1, 2025 23:28
Show Gist options
  • Save aerodame/c2789f35c57d9a5f5f61935f41a41bc5 to your computer and use it in GitHub Desktop.
Save aerodame/c2789f35c57d9a5f5f61935f41a41bc5 to your computer and use it in GitHub Desktop.
#include "MutexSemaphore.h"
Semaphore::Semaphore(int initialValue) : S(initialValue) {}
void Semaphore::P() {
std::unique_lock<std::mutex> lock(mutex_); // Acquire mutex
cv_.wait(lock, [this] { return S > 0; }); // Wait until S > 0
S--;
}
void Semaphore::V() {
std::lock_guard<std::mutex> lock(mutex_); // Acquire mutex
S++;
cv_.notify_one(); // Notify a waiting thread
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment