Skip to content

Instantly share code, notes, and snippets.

@anderspitman
Created August 5, 2016 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anderspitman/f2e92b4c458b5208d0249f1dff3dbea7 to your computer and use it in GitHub Desktop.
Save anderspitman/f2e92b4c458b5208d0249f1dff3dbea7 to your computer and use it in GitHub Desktop.
typedef struct Mutex {
int locked;
} Mutex;
typedef struct Semaphore {
int count;
Mutex mutex;
} Semaphore;
void mutex_init(Mutex *mut);
void mutex_lock(Mutex *mut);
void mutex_unlock(Mutex *mut);
void semaphore_init(Semaphore *sem, int value);
void semaphore_wait(Semaphore *sem);
void semaphore_signal(Semaphore *sem);
void shift(int *a, int *b);
int main() {
Semaphore sem;
semaphore_init(&sem, 1);
return 0;
}
void semaphore_init(Semaphore *sem, int value) {
mutex_init(&(sem->mutex));
sem->count = value;
}
void semaphore_wait(Semaphore *sem) {
int count = 0;
while (count <= 0) {
mutex_lock(&(sem->mutex));
count = sem->count;
mutex_unlock(&(sem->mutex));
}
mutex_lock(&sem->mutex);
sem->count--;
mutex_unlock(&sem->mutex);
}
void semaphore_signal(Semaphore *sem) {
mutex_lock(&sem->mutex);
sem->count++;
mutex_unlock(&sem->mutex);
}
void mutex_init(Mutex *mut) {
mut->locked = 0;
}
void mutex_lock(Mutex *mut) {
int temp = 0;
while (temp == 0) {
shift(&(mut->locked), &temp);
}
}
void mutex_unlock(Mutex *mut) {
mut->locked = 1;
}
void shift(int *a, int *b) {
*b = *a;
*a = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment