Try, for instance (see
Using Condition Variables (Multithreaded Programming Guide)[
^])
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * inc_func(void * arg);
void * wait_for_twenty_func(void * arg);
int g = 1;
int main()
{
pthread_t thr[2];
pthread_t thr_w;
for(int i = 0; i < 2; i++)
{
pthread_create(&thr[i] , NULL , inc_func , &g);
}
pthread_create(&thr_w , NULL , wait_for_twenty_func , NULL);
for(int i = 0; i < 2; i++)
{
pthread_join(thr[i] , NULL);
}
pthread_join(thr_w , NULL);
printf("\nCount finished...\n");
return 0;
}
void * inc_func(void * arg)
{
for(int i = 0; i < 10; i++)
{
pthread_mutex_lock(&my_mutex);
printf("g = %d\n" , g);
if ( g < 20)
{
g++;
pthread_cond_signal(&cond); }
pthread_mutex_unlock(&my_mutex);
}
return NULL;
}
void * wait_for_twenty_func(void * arg)
{
int is_twenty = 0;
while (! is_twenty )
{
pthread_mutex_lock(&my_mutex);
pthread_cond_wait(&cond, &my_mutex); printf("wait expired\n");
is_twenty = (g==20);
pthread_mutex_unlock(&my_mutex);
}
printf("twenty reached\n");
return NULL;
}