Skip to content

Instantly share code, notes, and snippets.

@aerodame
Last active February 1, 2025 23:50
Show Gist options
  • Save aerodame/c81f3659fb58a019ba9231e97b3320e5 to your computer and use it in GitHub Desktop.
Save aerodame/c81f3659fb58a019ba9231e97b3320e5 to your computer and use it in GitHub Desktop.
public class Semaphore {
private int S;
private Queue<Process> list; // Use a Queue to represent the process list
public Semaphore(int permits) {
this.S = permits;
this.list = new LinkedList<>(); // Initialize the process list
}
public synchronized void P(Process process) { // "P" operation (wait/acquire)
S--;
if (S < 0) {
list.add(process); // Queue a process
try {
wait(); // Wait on the semaphore object
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public synchronized void V() { // "V" operation (signal/release)
S++;
if (S <= 0) { // There are waiting processes
Process process = list.poll();
if (process != null) {
notify(); // Notify a waiting thread on the semaphore object
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment