I hope you will be able to help me in my trouble. My program is doing something I don't really understand. The program purpose is given as below: Create two threads (task_timer and task_read). These threads have to display on the standard output (stdout) the following message : "Tache 1 Tache 2 Tache 1 Tache 2 ..."
Code :
static void* task_timer(void* arg);
static void* task_read(void* p);
struct strShared{
pthread_mutex_t mut;
pthread_mutex_t mut2;
pthread_cond_t synchro;
pthread_cond_t synchro2;
};
struct strTimer{
int wt;
strShared* psh;
};
static void* task_timer(void* p){
time_t echeance;
strTimer* timer;
int time_waiting = 1000;
time_t now;
if(p != NULL){
timer = p;
time_waiting = timer->wt; //ms
echeance = time (NULL) + TIME_OF_THREAD;
while (1)
{
pthread_mutex_lock(&timer->psh->mut);
printf("Tache 1\n");
pthread_cond_signal(&timer->psh->synchro);
pthread_cond_wait(&timer->psh->synchro2, &timer->psh->mut);
pthread_mutex_unlock(&timer->psh->mut);
}
}
return NULL;
}
static void* task_read(void* p){
strTimer* timer;
if(p != NULL){
timer = p;
while(1){
pthread_mutex_lock(&timer->psh->mut);
pthread_cond_wait(&timer->psh->synchro, &timer->psh->mut);
printf("Tache 2\n");
pthread_cond_signal(&timer->psh->synchro2);
pthread_mutex_unlock(&timer->psh->mut);
}
}
return NULL;
}
int main (void)
{
pthread_t ttimer;
pthread_t tread;
/* TIMER */
strTimer timer;
strShared shtimer;
shtimer.mut = PTHREAD_MUTEX_INITIALIZER;
shtimer.mut2 = PTHREAD_MUTEX_INITIALIZER;
shtimer.synchro = PTHREAD_COND_INITIALIZER;
shtimer.synchro2 = PTHREAD_COND_INITIALIZER;
timer.psh = &shtimer;
timer.wt = 1000;
/* Threads */
pthread_create(&ttimer, NULL, task_timer, &timer);
pthread_create(&tread, NULL, task_read, &timer);
pthread_join(ttimer,NULL);
pthread_join(tread,NULL);
return 0;
}
According to me, this code is the good way to achieve this aim. However, it is not working then I guess I did some mistakes. According to me it is working as below:
- Both threads are created and executed in paralelism
- Task_read take the mutex mut, wait for the signal synchro and free the mutex because the signal is never arrived
- Task_timer take the mutex mut and display "Tache 1" on the standard output
- Then, Task_timer sends the signal synchro and waits for the signal synchro2 (free the mutex because the signal is never arrived)
- Task_read receives the signal synchro and take the mutex mut and displays "Tache 2"
- Task_read sends the signal synchro2 and free the mutex mut and go to the begining of the While loop
- Task_timer receives the signal synchro2 and free the mutex and go to the begining of the While loop
However, this is not happened like that. Actually, it seems the program gets stuck after displaying "Tache 1". Someone could explain me why this happens please ? I guess I think bad but I would like to understand ...
Many thanks, esc39