Here the new code snippet:
#define SIMU_TIME 30
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER ;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER ;
void *timer(void *Ptr)
{ while ((float) clock()/CLOCKS_PRE_TICKS < SIMU_TIME)
{ float mean = (float) Ptr ;
float interval = exponential(mean) ;
float goal = (float) clock()/CLOCKS_PRE_TICKS + interval ;
pthread_mutex_lock(&mutex) ;
while(goal > (float) clock()/CLOCKS_PRE_TICKS ) ;
pthread_mutex_unlock(&mymutex) ;
}
return(NULL) ;
}
void *AddPacket(void *Ptr)
{
pthread_cond_lock(&mymutex) ;
pthread_cond_wait(&condition, &mymutex) ;
// do business
pthread_unlock_mutex(&mymutex) ;
}
int main()
{ float mean = 1.5 ;
pthread_t thread1, thread2 ;
pthread_create(&thread1, NULL, &timer, (void *) mean) ;
pthread_create(&thread2, NULL, &AddPacket, NULL) ;
pthread_join(thread1, NULL) ;
pthread_join(thread2, NULL) ;
pthread_mutex_destroy(&mymutex) ;
pthread_cond_destroy(&condition) ;
pthread_exit(NULL) ;
}
Since the pthread_cond_wait is used generally when one thread doesn't access to an attribut until it reaches a certain threshold, we must use a mutex associated with this variable to avoid any race conditions, but in my case, the two threads don't actually need to access to the same memory area, it's just a way to schedule the second thread when the first one allows it. In this situation is it necessary to call "pthread_mutex_lock" before "pthread_cond_wait" ?