Codice: Seleziona tutto
/*multi threads execution simple exemple*/
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void *funz1(void *x)
{
printf("1) Starting 1st Thread...\n");
sleep(1);
/*aquisisce il lock*/
pthread_mutex_lock(&condition_mutex);
printf("3) 1st Thread waits 2nd Thread completes his execution...\n");
sleep(1);
/*aspetta l'esecuzione di un altro thread*/
pthread_cond_wait(&condition_cond, &condition_mutex);
sleep(1);
pthread_mutex_unlock(&condition_mutex);
printf("5) 1st Thread completes his execution...\n\n");
return 0;
}
void *funz2(void *x)
{
printf("2) Starting 2nd Thread...\n");
sleep(1);
/*aquisisce il lock*/
pthread_mutex_lock(&condition_mutex);
sleep(1);
/*riceve il segnale di precendenza per l'esecuzione*/
pthread_cond_signal(&condition_cond);
sleep(1);
pthread_mutex_unlock(&condition_mutex);
printf("4) 2nd Thread executed...\n");
return 0;
}
int main()
{
pthread_t t1, t2;
printf("\n**Starting execution of threads**\n\n");
if(pthread_create(&t1, NULL , funz1, NULL) != 0)
{
printf("Error generating threads\n");
return 1;
}
if(pthread_create(&t2, NULL , funz2, NULL) != 0)
{
printf("Error generating threads\n");
return 1;
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
Su una ubuntu il risultato è quello "voluto"; ossia 1, 2, 3, 4, 5 in ordine..
Sulla mia slack 12.2 invece ci sono problemi: dopo il 4 si blocca, in uno sleep senza limite di tempo..
Codice: Seleziona tutto
**Starting execution of threads**
1) Starting 1st Thread...
2) Starting 2nd Thread...
3) 1st Thread waits 2nd Thread completes his execution...
4) 2nd Thread executed...
^C
simo@localhost:
Codice: Seleziona tutto
**Starting execution of threads**
1) Starting 1st Thread...
3) 1st Thread waits 2nd Thread completes his execution...
2) Starting 2nd Thread...
5) 1st Thread completes his execution...
4) 2nd Thread executed...
Grazie a tutti!