Nyquister

Thread_esercitation

Apr 6th, 2021 (edited)
626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. /*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*/
  2.  
  3. #include<stdlib.h>
  4. #include<stdio.h>
  5. #include<unistd.h>
  6. #include<pthread.h>
  7. #include<string.h>
  8.  
  9.  
  10. int I,*n;
  11.  
  12. int error(char *er, int ern)
  13. {printf("Error!Unable to %s %d\n",er,ern);
  14.  return -1;
  15. }
  16.  
  17. void debug(char *db)
  18. {printf("\n\nDebug point %s\n\n",db);
  19. }
  20.  
  21. void *thread_rw(void *b)
  22. {char *s;
  23.  if(I>0)
  24.     printf("The message from thread %d is: %s\n",I,(char*)b);
  25.  if(I<*n-1)
  26.     {printf("Insert a message for thread %d: \n\n",I+1);  
  27.     scanf("%m[^\n]",&s);
  28.     while (getchar() != (int)'\n');
  29.     /*Non inserendo questa while la scanf all'interno di questo
  30.     thread viene completamente bypassata restituendo N thread
  31.     che ricevono messaggi NULL, questo bypass nel caso di un
  32.     singolo thread non sussiste non riesco a capirne il motivo?*/
  33.     }  
  34.  pthread_exit((void *)s);  
  35.  }
  36.  
  37. void main(int argc, char*argv[])
  38. {pthread_t t;
  39.  void *buff;
  40.  n=malloc(8);
  41.  printf("Insert the number of thread you desire:");
  42.  scanf("%d",n);
  43.  while (getchar() != (int)'\n');
  44. /*Senza inserire questa while il primo thread bypassa la scanf
  45. ed al secondo viene passato un messaggio NULL, non ne riesco a
  46. capire la motivazione?*/
  47.  for(I=0;I<*n;I++)  
  48.     {if(pthread_create(&t,NULL,thread_rw,buff))
  49.         error("create thread!",I);
  50.      if(pthread_join(t,&buff)==-1)
  51.         error("wait thread!",I);
  52.     }    
  53. }
Add Comment
Please, Sign In to add comment