Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <sys/syscall.h>
- #include <errno.h>
- #include <sys/time.h>
- #define EURO 100000000
- long int deposito,preso1=0,preso2=0;
- pid_t gettid() { return syscall( __NR_gettid ); }
- void *prelievo(void *p)
- {
- long int *preso;
- preso=(long int *)p;
- printf("ID del thread prelievo: %lu\n", (unsigned long)gettid());
- while (1)
- {
- if (deposito == 0)
- { break; }
- deposito--; /** Diminusce di 1 il deposito.. */
- (*preso)++; /** ... e incrementa di uno i solti ritirati.. */
- }
- return NULL;
- }
- int main()
- {
- pthread_t thr1, thr2;
- struct timeval tv1, tv2;
- deposito=EURO;
- /** Prendiamo il tempo **/
- gettimeofday(&tv1, NULL);
- pthread_create(&thr1, NULL, prelievo, &preso1);
- pthread_create(&thr2, NULL, prelievo, &preso2);
- pthread_join(thr1, NULL);
- pthread_join(thr2, NULL);
- /** Prendiamo di nuovo il tempo alla fine **/
- gettimeofday(&tv2, NULL);
- if (tv1.tv_usec > tv2.tv_usec)
- { tv2.tv_sec--; tv2.tv_usec += 1000000; }
- printf("Tempo impiegato: %ld.%ld secondi\n", tv2.tv_sec - tv1.tv_sec, tv2.tv_usec - tv1.tv_usec);
- printf("Risultati - Presi dal primo thread: %ld; dal secondo %ld\n", preso1,preso2);
- if (preso1+preso2==EURO)
- printf("Tutto OK\n");
- else
- printf("I conti non tornano, la differenza è %ld Euro.\n",preso2-preso1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement