Consider the following program:
// Compilation:
// gcc -Wall -Wextra -pedantic -Wno-unused-parameter -O3 test.c -o test -pthread
// Include
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
// Common variables
sem_t sem; // Semaphore
static const int nthr = 4; // Number of threads
static int n = 0; // Global counter
// Wait for a given number of seconds
void wait(unsigned int seconds)
{
unsigned int limit = time(NULL) + seconds;
while (time(NULL) < limit);
}
// Function f0
void* f0(void* arg)
{
while (n < 2); // Here
// Doing stuff that does no require any access to shared variable
printf("...doing stuff in f0...\n");
pthread_exit(NULL);
}
// Function fn
void* fn(void* arg)
{
sem_wait(&sem);
wait(1);
printf("entering fn: n = %d\n", n);
n++;
printf("leaving fn: n = %d\n", n);
wait(1);
sem_post(&sem);
pthread_exit(NULL);
}
// Main
int main(int argc, char* argv[])
{
pthread_t thr[nthr];
sem_init(&sem, 0, 1);
pthread_create(&thr[0], NULL, f0, NULL);
for (int i = 1; i < nthr; ++i) pthread_create(&(thr[i]), NULL, fn, NULL);
for (int i = 0; i < nthr; ++i) pthread_join(thr[i], NULL);
return 0;
}
The program does the following:
thread0
executes f0
while the other threads are executing fn
. I would like f0
to wait until two threads have incremented n
before doing something.
Currently line marked Here
should do that, but it does not work. How to do it properly (using semaphores instead of mutexes when possible)?