My goal is this:
I want to have multiple threads running the same function, the function is a while(1) loop so it just goes on. At some point main should use a mutex to force all threads to block until main (or something else) signals them to continue at which point they all continue until they get forced to block them.
The threads should run in parallel
I have tried to use pthread_cond_wait() for the threads to wait and pthread_cond_broadcast() to let them continue but it does not work at all
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t mtx;
pthread_cond_t cv;
void* func(void* arg) {
while (1) {
pthread_mutex_lock(&mtx);
pthread_cond_wait(&cv, &mtx);
printf("Thread %lu is running.n", pthread_self());
pthread_mutex_unlock(&mtx);
usleep(500000);
}
}
int main() {
pthread_t threads[2];
pthread_mutex_init(&mtx, NULL);
pthread_cond_init(&cv, NULL);
for (int i = 0; i < 2; ++i) {
pthread_create(&threads[i], NULL, func, NULL);
}
pthread_mutex_unlock(&mtx);
pthread_cond_broadcast(&cv);
sleep(2);
pthread_mutex_lock(&mtx);
sleep(2);
pthread_mutex_unlock(&mtx);
pthread_cond_broadcast(&cv);
sleep(2);
return 0;
}