Advertisement
modellking

Find max in array with thread

Jan 28th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <math.h>
  4.  
  5. typedef struct {
  6.     int **startat;
  7.     int *docount;
  8. } thread_arg;
  9.  
  10. /* This is our thread function.  It is like main(), but for a thread*/
  11. int *threadFunc(void *args)
  12. {
  13.     thread_arg *aargs = args;
  14.     int erg = 0;
  15.     for (int i = 0; i < aargs->docount; ++i) {
  16.         if(aargs->startat + i > erg) {
  17.             erg = aargs->startat + i;
  18.         }
  19.     }
  20.     free(aargs);
  21.  
  22.     return erg;
  23. }
  24.  
  25. int main(void)
  26. {
  27.     int length = 100;
  28.     int in[length];
  29.     for (int i = 0;i < length; ++i) {
  30.         in[i] = rand();
  31.     }
  32.     int threads = (int) 1+sqrt(length-10); // we want to use sqrt(length) threads in an ideal szenario without slowdown when creating them. 10 is a threshhold for this
  33.     int threadstepsize = (int) 1+length/threads;
  34.    
  35.     int ret = -1;
  36.    
  37.     pthread_t * thread = malloc(sizeof(pthread_t)*threads);
  38.    
  39.     for (int i = 0; i < threads; ++i) {
  40.         thread_arg *args = malloc(sizeof *args);
  41.         args->startat = in[i*threadstepsize];
  42.         args->docount = &threadstepsize;
  43.         ret = pthread_create(&thread[i], NULL, threadFunc, args);
  44.        
  45.         if(ret != 0) {
  46.             printf ("Create pthread error!\n");
  47.             exit (1);
  48.         }
  49.     }
  50.     printf("main waiting for threads to terminate...\n");
  51.     int out[threads];
  52.     for (int i = 0; i < threads; ++i) {
  53.         pthread_join(thread[i],out[i]);
  54.     }
  55.     thread_arg *args = malloc(sizeof *args);
  56.     args->startat = &out;
  57.     args->docount = &threads;
  58.     int erg = threadFunc(args);
  59.     printf("max is %d\n",erg);
  60.    
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement