Skip to content

Instantly share code, notes, and snippets.

@anderspitman
Created August 5, 2016 22:42
Show Gist options
  • Save anderspitman/c454f795e88a1aa85faf4ced524d87f2 to your computer and use it in GitHub Desktop.
Save anderspitman/c454f795e88a1aa85faf4ced524d87f2 to your computer and use it in GitHub Desktop.
#include <stdio.h>
typedef struct Semaphore {
} Semaphore;
void semaphore_init(Semaphore *sem, int value);
void semaphore_wait(Semaphore *sem);
void semaphore_signal(Semaphore *sem);
Semaphore p1Ready;
Semaphore p1New;
Semaphore p2Ready;
Semaphore p2New;
Semaphore p3Ready;
Semaphore p3New;
int x;
int main() {
// Will start by p0 waiting on p1-p3. That way they have an opportunity
// to print the first value which is '0'.
semaphore_init(&p1Ready, 0);
semaphore_init(&p1New, 1);
semaphore_init(&p2Ready, 0);
semaphore_init(&p2New, 1);
semaphore_init(&p3Ready, 0);
semaphore_init(&p3New, 1);
x = 0;
// Start processes...
return 0;
}
void process0() {
while (1) {
semaphore_wait(&p1Ready);
semaphore_wait(&p2Ready);
semaphore_wait(&p3Ready);
x++;
semaphore_signal(&p1New);
semaphore_signal(&p2New);
semaphore_signal(&p3New);
}
}
void process1() {
while (1) {
semaphore_wait(&p1New);
printf("Process 1 says: %d", x);
semaphore_signal(&p1Ready);
}
}
void process2() {
while (1) {
semaphore_wait(&p2New);
if (x % 2 == 0) {
printf("Process 2 says: %d", x);
}
semaphore_signal(&p2Ready);
}
}
void process3() {
while (1) {
semaphore_wait(&p3New);
if (x % 3 == 0) {
printf("Process 3 says: %d", x);
}
semaphore_signal(&p3Ready);
}
}
void semaphore_init(Semaphore *sem, int value) {
}
void semaphore_wait(Semaphore *sem) {
}
void semaphore_signal(Semaphore *sem) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment