Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Scrivere un programma il cui processo principale genera N threads.Ogni thread,con indice i,chiede all’utente di inserire un messaggio per il thread con indice i+1. Ogni thread, con indice i, come prima cosa stampa il messaggio ricevuto dal thread con indice i-1 .Le operazioni di lettura del messaggio ricevuto dal thread precedente, stampa del messaggio e richiesta di un nuovo messaggio per il thread successivo, devono essere sequenzializzate*/
- #include<stdlib.h>
- #include<stdio.h>
- #include<unistd.h>
- #include<pthread.h>
- #include<string.h>
- int I,*n;
- int error(char *er, int ern)
- {printf("Error!Unable to %s %d\n",er,ern);
- return -1;
- }
- void debug(char *db)
- {printf("\n\nDebug point %s\n\n",db);
- }
- void *thread_rw(void *b)
- {char *s;
- if(I>0)
- printf("The message from thread %d is: %s\n",I,(char*)b);
- if(I<*n-1)
- {printf("Insert a message for thread %d: \n\n",I+1);
- scanf("%m[^\n]",&s);
- while (getchar() != (int)'\n');
- /*Non inserendo questa while la scanf all'interno di questo
- thread viene completamente bypassata restituendo N thread
- che ricevono messaggi NULL, questo bypass nel caso di un
- singolo thread non sussiste non riesco a capirne il motivo?*/
- }
- pthread_exit((void *)s);
- }
- void main(int argc, char*argv[])
- {pthread_t t;
- void *buff;
- n=malloc(8);
- printf("Insert the number of thread you desire:");
- scanf("%d",n);
- while (getchar() != (int)'\n');
- /*Senza inserire questa while il primo thread bypassa la scanf
- ed al secondo viene passato un messaggio NULL, non ne riesco a
- capire la motivazione?*/
- for(I=0;I<*n;I++)
- {if(pthread_create(&t,NULL,thread_rw,buff))
- error("create thread!",I);
- if(pthread_join(t,&buff)==-1)
- error("wait thread!",I);
- }
- }
Add Comment
Please, Sign In to add comment