Created
October 26, 2014 19:00
-
-
Save joshblack/5493b50b32c789b0becd to your computer and use it in GitHub Desktop.
semaphore solution for OS exam
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
#define N // number of buffers | |
int in = 0, out = 0; // Reader and writer pointers to buffer spaces | |
// Semaphores | |
resources = 0; // number of resources that we are producing | |
buffer = N; // buffer space | |
mutex = 1; // Mutual exclusion to make sure we aren't reading and writing at the same time | |
criticalA = 1; // critical A and B are used to enforce the requirement that we produce A, then B, then A, etc... | |
criticalB = 1; | |
producerA(res A) { | |
down(buffer); | |
down(mutex); | |
down(criticalB); | |
// write resource A to buffer | |
up(criticalA); | |
up(mutex); | |
up(resources); | |
} | |
producerB(res B) { | |
down(buffer); | |
down(mutex); | |
down(criticalA); | |
// write resource B to buffer | |
up(criticalB); | |
up(mutex); | |
up(resources); | |
} | |
res consumer() { | |
down(mutex); | |
down(resources); | |
// read index, index + 1 from buffer | |
up(buffer); | |
up(buffer); // up buffer twice since we consume two resources | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment