Skip to content

Instantly share code, notes, and snippets.

@onlined
Created September 4, 2018 07:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onlined/7b5923d7912724ed33e230a01a7ab9af to your computer and use it in GitHub Desktop.
Save onlined/7b5923d7912724ed33e230a01a7ab9af to your computer and use it in GitHub Desktop.
A semaphore implementation with C11 threading libraries
#include <threads.h>
typedef struct {
int value;
mtx_t mutex;
cnd_t cv;
} sem_t;
int sem_init(sem_t *sem, int value) {
int result;
if (mtx_init(&sem->mutex, mtx_plain) == thrd_error)
return thrd_error;
if ((result = cnd_init(&sem->cv)) == thrd_error || result == thrd_nomem)
return thrd_error;
sem->value = value;
return thrd_success;
}
void sem_destroy(sem_t *sem) {
mtx_destroy(&sem->mutex);
cnd_destroy(&sem->cv);
sem->value = 0;
}
int sem_wait(sem_t *sem) {
if (mtx_lock(&sem->mutex) == thrd_error)
return thrd_error;
while (sem->value == 0) {
if (cnd_wait(&sem->cv, &sem->mutex) == thrd_error)
return thrd_error;
}
sem->value--;
if (mtx_unlock(&sem->mutex) == thrd_error)
return thrd_error;
return thrd_success;
}
int sem_post(sem_t *sem) {
if (mtx_lock(&sem->mutex) == thrd_error)
return thrd_error;
sem->value++;
if (sem->value > 0)
if (cnd_signal(&sem->cv) == thrd_error)
return thrd_error;
if (mtx_unlock(&sem->mutex) == thrd_error)
return thrd_error;
return thrd_success;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment