Advertisement
piffy

pthread

Sep 1st, 2014 (edited)
476
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #define NUM_THREADS 16
  6. /**********************************
  7.  * compilare con                  *
  8.  * cc pthread.c -pthread -lm    *
  9.  **********************************/
  10. void *operaio(void *t)
  11. {
  12.    int i;
  13.    long n;
  14.    pthread_t ThId= pthread_self();
  15.    double risultato=0.0;
  16.    n = (long)t;
  17.    printf("Thread numero %ld (con ThreadID %ld) partito...\n",n,ThId);
  18.    for (i=0; i<1000000; i++)
  19.    {
  20.       risultato = risultato + sin(i) * tan(i);
  21.    }
  22.    printf("Thread %ld terminato. Risultato = %e\n",n, risultato);
  23.    pthread_exit((void*) t);
  24. }
  25.  
  26. int main (int argc, char *argv[])
  27. {
  28.    pthread_t thread[NUM_THREADS];
  29.    int ret;long t;
  30.    void *status;
  31.  
  32.    /* Boss: inizializza i thread  */
  33.    for(t=0; t<NUM_THREADS; t++) {
  34.       printf("Main: creating thread %ld\n", t);
  35.       ret = pthread_create(&thread[t], NULL, operaio, (void *)t);
  36.       if (ret) {printf("ERR: pthread_create() ha restituito %d\n", ret);
  37.          exit(-1);}
  38.       }
  39.  
  40.    /* Boss: aspetta il termine dei thread */
  41.    for(t=0; t<NUM_THREADS; t++) {
  42.       ret = pthread_join(thread[t], &status);
  43.       if (ret) {printf("ERR: pthread_join() ha restituito %d\n", ret);
  44.          exit(-1);}
  45.       printf("main(): riunito thread %ld (status=%ld)\n",t,(long)status);
  46.       }
  47.  
  48. printf("main(): fine esecuzione.\n");
  49. pthread_exit(EXIT_SUCCESS);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement