Using this section of code below as an example (courtesy of https://www.geeksforgeeks.org/condition-wait-signal-multi-threading/) what would be the method of converting a pthread_mutex_lock()
and pthread_mutex_unlock()
to POSIX and achieve mutual exclusion between functions.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int done = 1;
void* foo()
{
pthread_mutex_lock(&lock);
if (done == 1) {
done = 2;
printf("Waiting on condition variable cond1\n");
pthread_cond_wait(&cond1, &lock);
}
else {
printf("Signaling condition variable cond1\n");
pthread_cond_signal(&cond1);
}
pthread_mutex_unlock(&lock);
printf("Returning thread\n");
return NULL;
}