Skip to content

Instantly share code, notes, and snippets.

@psqli
Last active September 15, 2016 16:56
Show Gist options
  • Save psqli/61e9496dad3ad0014855cfe0b090a45b to your computer and use it in GitHub Desktop.
Save psqli/61e9496dad3ad0014855cfe0b090a45b to your computer and use it in GitHub Desktop.
increment based mutex
/* We have two sides which can lock our vmutexes:
* 1st side uses acquire/release functions and it can only hold mutex when
* `counter` is zero. If counter is not zero `acquire` waits.
* 2nd side uses increment/decrement functions and when it holds mutex it
* increments `counter`. This side can't hold mutex while 1st side is already
* holding it.
*/
#include <pthread.h>
#include <stdlib.h>
typedef struct {
pthread_mutex_t control;
unsigned int counter;
pthread_cond_t cond;
} vmutex_t;
void
vmutex_init (vmutex_t *vmtx) {
pthread_mutex_init(&vmtx->control, NULL);
pthread_cond_init(&vmtx->cond, NULL);
vmtx->counter = 0;
}
void
vmutex_destroy (vmutex_t *vmtx) {
pthread_mutex_destroy(&vmtx->control);
pthread_cond_destroy(&vmtx->cond);
}
void
vmutex_increment (vmutex_t *vmtx) {
pthread_mutex_lock(&vmtx->control);
vmtx->counter++;
pthread_mutex_unlock(&vmtx->control);
}
void
vmutex_decrement (vmutex_t *vmtx) {
pthread_mutex_lock(&vmtx->control);
vmtx->counter--;
if(!vmtx->counter)
pthread_cond_signal(&vmtx->cond);
pthread_mutex_unlock(&vmtx->control);
}
void
vmutex_acquire (vmutex_t *vmtx) {
pthread_mutex_lock(&vmtx->control);
if(vmtx->counter)
pthread_cond_wait(&vmtx->cond, &vmtx->control);
}
void
vmutex_release (vmutex_t *vmtx) {
pthread_mutex_unlock(&vmtx->control);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment