In C++ it's recommended to use lock_guard as it ensures when the object is destroyed it unlocks the mutex.
Is there a way to implement the same thing in C? Or do we have to just implement it manually:
lock mutex
Do something on a global variable
unlock mutex
#include <stdio.h>
#include <threads.h>
long long x = 0;
mtx_t m;
static void do1() {
mtx_lock(&m);
for(int i = 0; i < 100; i++){
x = x +1;
}
mtx_unlock(&m);
}
static void do2() {
mtx_lock(&m);
x = x / 3;
mtx_unlock(&m);
}
int main(int argc, char *argv[])
{
mtx_init(&m, mtx_plain);
thrd_t thr1;
thrd_t thr2;
thrd_create(&thr1, do1, 0);
thrd_create(&thr2, do2, 0);
thrd_join(&thr2, 0);
thrd_join(&thr1, 0);
return 0;
}