Is there a way to make it so I can have n threads run a certain function when other threads are not locking other functions?
I want to achieve something like:
pthread_t threadID[10];
pthread_mutex_t blocking;
pthread_mutex_init(&blocking, NULL);
pthread_cond_t go;
pthread_cond_init(&go, NULL);
void * function1() {
pthread_mutex_lock(&blocking); // Only one thread at a time!
// Do some work
pthread_cond_broadcast(&go);
pthread_mutex_unlock(&blocking);
}
void * function2() {
pthread_cond_wait(&go, NULL); // Imagine 5 threads waiting here.
// Does some work too!
}
What I want is basically that n threads run function2, when no threads are running in function1.
I do not wish to lock function2 as threads may execute it concurrently without a problem, so I know the pthread_cond_wait(&go, NULL) will not work (even the NULL argument is a bit silly). Also, a broadcast will signal all waiting threads, but only one of those threads will make it to the critical code section. I'm aiming to unlock all threads with a signal, and allow all those threads to execute the code.
I know there are ways to do this without going into thread locking mechanisms (like having a variable be modified inside function1 and function2 must check its value before allowing threads to move forward), but I was wondering if there is a way with mutexes and condition variables, not semaphores.