come faccio a creare tre thread e farli eseguire uno dopo l'altro.
esempio
un thread stampa A un altro stampa B e il terzo stampa C
io come risultato devo avere SEMPRE ABCABC...
la soluzione con i turni funziona solo con 2 thread
posto la soluzione che non funziona.. anche se è inutile..
codice:#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> //puntatore ad area di memoria condivisa int *a; int turno = 0; //0=turno produttore 1=turn consum pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione = PTHREAD_COND_INITIALIZER; void *thread_p1(void *d) { while (1) { pthread_mutex_lock(&lock); if (turno == 1) { pthread_cond_wait(&condizione, &lock); } printf("A"); turno = 1; pthread_cond_signal(&condizione); pthread_mutex_unlock(&lock); } } void *thread_p2(void *d) { while (1) { pthread_mutex_lock(&lock); if (turno == 0) { pthread_cond_wait(&condizione, &lock); } printf("B"); turno = 0; pthread_cond_signal(&condizione); pthread_mutex_unlock(&lock); } } void *thread_p3(void *d) { while (1) { pthread_mutex_lock(&lock); if (turno == 2) { pthread_cond_wait(&condizione, &lock); } printf("C"); turno = 2; pthread_cond_signal(&condizione); pthread_mutex_unlock(&lock); } } int main(int argc, char **argv) { printf("tutto ok\n"); //alloco memoria a = calloc(2, sizeof (int)); pthread_t th1, th2, th3; pthread_create(&th1, NULL, thread_p1, NULL); pthread_create(&th2, NULL, thread_p2, NULL); pthread_create(&th3, NULL, thread_p3, NULL); pthread_detach(th1); pthread_detach(th2); pthread_detach(th3); pthread_exit(NULL); return 0; }

Rispondi quotando

