Advertisement
piffy

condiv_1.5.6esercizio5

Sep 4th, 2014
451
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <sys/syscall.h>
  5. #include <errno.h>
  6. #include <sys/time.h>
  7. #define EURO 100000000
  8.  
  9. long int deposito,preso1=0,preso2=0;
  10.  
  11. pid_t gettid() { return syscall( __NR_gettid ); }
  12.  
  13. void *prelievo(void *p)
  14. {
  15.     long int *preso;
  16.     preso=(long int *)p;
  17.     printf("ID del thread prelievo: %lu\n", (unsigned long)gettid());
  18.     while (1)
  19.     {
  20.         if (deposito == 0)
  21.         { break; }
  22.        deposito--; /** Diminusce di 1 il deposito.. */
  23.        (*preso)++; /** ... e incrementa di uno i solti ritirati.. */
  24.     }
  25.  
  26.     return NULL;
  27. }
  28.  
  29. int main()
  30. {
  31.     pthread_t thr1, thr2;
  32.     struct timeval tv1, tv2;
  33.     deposito=EURO;
  34.  
  35.     /** Prendiamo il tempo **/
  36.     gettimeofday(&tv1, NULL);
  37.  
  38.     pthread_create(&thr1, NULL, prelievo, &preso1);
  39.     pthread_create(&thr2, NULL, prelievo, &preso2);
  40.     pthread_join(thr1, NULL);
  41.     pthread_join(thr2, NULL);
  42.  
  43.     /** Prendiamo di nuovo il tempo alla fine **/
  44.     gettimeofday(&tv2, NULL);
  45.     if (tv1.tv_usec > tv2.tv_usec)
  46.     {   tv2.tv_sec--; tv2.tv_usec += 1000000;  }
  47.  
  48.     printf("Tempo impiegato: %ld.%ld secondi\n", tv2.tv_sec - tv1.tv_sec, tv2.tv_usec - tv1.tv_usec);
  49.     printf("Risultati - Presi dal primo thread: %ld; dal secondo %ld\n", preso1,preso2);
  50.     if (preso1+preso2==EURO)
  51.     printf("Tutto OK\n");
  52.     else
  53.     printf("I conti non tornano, la differenza è %ld Euro.\n",preso2-preso1);
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement