matheus__serpa

pthread_example

Sep 20th, 2017
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5.  
  6. long int MAX;
  7. long int sum = 0;
  8. long int n_threads;
  9. pthread_mutex_t lock;
  10.  
  11. void* somador(void *tid){
  12.     long int i, start, end, sum_local = 0;
  13.     long int *id = (long int *) tid;
  14.  
  15.     start = *id * (MAX / n_threads);
  16.     if(*id == n_threads - 1)
  17.         end = MAX;
  18.     else
  19.         end = start + (MAX / n_threads);
  20.    
  21.     for(i = start; i < end; i++)
  22.         sum_local++;
  23.  
  24.     printf("thread %ld - sum = %ld\n", *id, sum_local);
  25.  
  26.     pthread_mutex_lock(&lock);
  27.     sum += sum_local;
  28.     pthread_mutex_unlock(&lock);
  29.  
  30.  
  31.     pthread_exit(NULL);
  32. }
  33.  
  34. int main(int argc, char ** argv) {
  35.     if(argc != 3){
  36.         fprintf(stderr, "Usage: %s <n_threads> <max>\n", argv[0]);
  37.         exit(EXIT_FAILURE);
  38.     }
  39.     n_threads = atoi(argv[1]);
  40.     MAX = atoi(argv[2]);
  41.  
  42.     long int tid;
  43.     pthread_t *threads;
  44.     struct timespec start, finish;
  45.     double elapsed;
  46.  
  47.     threads = (pthread_t *) malloc(n_threads * sizeof(pthread_t));
  48.  
  49.     pthread_mutex_init(&lock, NULL);
  50.  
  51.     clock_gettime(CLOCK_MONOTONIC, &start);
  52.  
  53.     for(tid = 0; tid < n_threads; tid++)
  54.         pthread_create(&threads[tid], NULL, (void *) somador, (void *) &tid);
  55.  
  56.     for(tid = 0; tid < n_threads; tid++)
  57.         pthread_join(threads[tid], NULL);
  58.  
  59.     pthread_mutex_destroy(&lock);
  60.    
  61.     clock_gettime(CLOCK_MONOTONIC, &finish);
  62.     elapsed = (finish.tv_sec - start.tv_sec) + (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
  63.  
  64.     printf("\nTotal time: %.10f seconds\n\n", elapsed);
  65.  
  66.     printf("sum global = %ld\n", sum);
  67.  
  68.     free(threads);
  69.  
  70.     pthread_exit(NULL);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment