Created
November 5, 2015 09:00
-
-
Save niamster/937403d98d08448fcbbe to your computer and use it in GitHub Desktop.
RAII mutex pseudo in c
This file contains 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
#include <stdio.h> | |
#include <stdbool.h> | |
#include <assert.h> | |
typedef struct { | |
int locked; | |
} mutex_t; | |
static void mutex_init(mutex_t *mtx) { | |
mtx->locked = 0; | |
} | |
static void mutex_lock(mutex_t *mtx) { | |
++mtx->locked; | |
} | |
static void mutex_unlock(mutex_t *mtx) { | |
--mtx->locked; | |
} | |
typedef struct { | |
mutex_t *mtx; | |
bool locked; | |
} raii_mutex_t; | |
static void raii_mutex_cleanup(raii_mutex_t *mtx) { | |
if (mtx->locked) | |
mutex_unlock(mtx->mtx); | |
} | |
static void raii_mutex_lock(raii_mutex_t *mtx) { | |
if (mtx->locked) | |
return; | |
mutex_lock(mtx->mtx); | |
mtx->locked = true; | |
} | |
static void raii_mutex_unlock(raii_mutex_t *mtx) { | |
if (!mtx->locked) | |
return; | |
mutex_unlock(mtx->mtx); | |
mtx->locked = false; | |
} | |
#define raii_mutex(_name, _mtx) raii_mutex_t _name __attribute__((cleanup(raii_mutex_cleanup))) = {.mtx = (_mtx), .locked = false} | |
static void foo(mutex_t *mtx) { | |
raii_mutex(rmtx, mtx); | |
raii_mutex_lock(&rmtx); | |
assert(mtx->locked == true); | |
} | |
int main(int argc, char **argv) | |
{ | |
mutex_t mtx; | |
mutex_init(&mtx); | |
foo(&mtx); | |
assert(mtx.locked == false); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment