Advertisement
Guest User

Untitled

a guest
May 5th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. //
  2. // Created by bram on 5-5-16.
  3. //
  4. #include <stdio.h>
  5. #include <pthread.h>
  6.  
  7. #include "gemiddelde.h"
  8.  
  9. #define SIZE 100000
  10.  
  11. void *avg(void* args) {
  12.     printf("Starting up thread...");
  13.     float total = 0.0;
  14.     float *array = (float*)args;
  15.     int i;
  16.     for(i = 0; i < SIZE; i++)
  17.     {
  18.         total += array[i];
  19.     }
  20.    
  21.     float result = total/(float)SIZE;
  22.     float *ptr = &result;
  23.    
  24.     return (void*)ptr;
  25. }
  26.  
  27. int main()
  28. {
  29.     /* create threads */
  30.     pthread_t t1, t2, t3, t4;
  31.     if( pthread_create(&t1, NULL, avg, (void*)a1) ||
  32.         pthread_create(&t2, NULL, avg, (void*)a2) ||
  33.         pthread_create(&t3, NULL, avg, (void*)a3) ||
  34.         pthread_create(&t4, NULL, avg, (void*)a4) )
  35.     {
  36.         printf("ERROR CREATING THREADS");
  37.         return 1;
  38.     }
  39.    
  40.     /* get results */
  41.     void *total1, *total2, *total3, *total4;
  42.    
  43.     if( pthread_join(t1, total1)    ||
  44.         pthread_join(t2, total2)    ||
  45.         pthread_join(t3, total3)    ||
  46.         pthread_join(t4, total4)    )
  47.     {
  48.         printf("ERROR JOINING THREADS");
  49.         return 1;
  50.     }
  51.    
  52.     /* calculate total avg */
  53.     float total = *((float*)total1) + *((float*)total2) + *((float*)total3) + *((float*)total4);
  54.     total /= 4;
  55.    
  56.     printf("GEMIDDELDE: %.5f", total);
  57.    
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement