Last active
February 1, 2025 23:50
-
-
Save aerodame/c81f3659fb58a019ba9231e97b3320e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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