I’m trying to implement this simple example of how to synchronize threads using pthread library:
#include <iostream>
#include <pthread.h>
using namespace std ;
static pthread_mutex_t locker;
pthread_cond_t cond;
volatile bool ok=false;
void *func2(void *data)
{
int i;
for(i=0;i<100;i++)
{
pthread_mutex_lock (&locker);
cout << "1";
pthread_mutex_unlock(&locker);
if(i==10)
{
ok=true;
pthread_cond_signal(&cond);
}
}
pthread_exit(0);
}
void *fun1(void *data)
{
int i;
for(i=0;i<100;i++)
{
if(ok==false){
pthread_cond_wait(&cond, &locker);
}
pthread_mutex_lock (&locker);
cout << "2";
pthread_mutex_unlock(&locker);
}
pthread_exit(0);
}
int main(void)
{
pthread_t thread1, thread2;
void *retour_thread;
pthread_mutex_init (&locker, NULL);
pthread_cond_init(&cond, NULL);
if(pthread_create (&thread1, NULL, fun1, NULL) < 0)
{
cout << "problem thread";
exit(1);
}
if(pthread_create (&thread2, NULL, func2, NULL) < 0)
{
cout << "problem thread";
exit(1);
}
(void)pthread_join(thread1,&retour_thread);
(void)pthread_join(thread2,&retour_thread);
return 0;
}
what should I see is func1 wait until the condition (ok==true) then process func2…but what I’m getting is unpredictable and not synchrinised!!!
any help and thanks in advence
You need to acquire the mutex before you call pthread_cond_wait, and after pthread_cond_wait returns, the mutex is reacquired. Your fun1() should look something like:
Update:
You have a race where func2() can signal faster than fun1() can consume. If you want alternate “1” and “2” outputs, you need feedback in both directions.