Advertisement
Guest User

Untitled

a guest
May 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <time.h>
  5.  
  6. pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
  7.  
  8. typedef struct{
  9.     int first;
  10.     int second;
  11.     int ind;
  12. }Pair;
  13.  
  14. Pair pair;
  15. int has_ended = 0, n = 0;
  16.  
  17. void* count(void* my_pair){
  18.     int first = ((Pair*)my_pair)->first;
  19.     int second =((Pair*)my_pair)->second;
  20.     int id = ((Pair*)my_pair)->ind;
  21.     printf("On thread %d start the sum was: %d, first was %d, second was %d\n", id, n, first, second);
  22.     pthread_mutex_lock(&mtx);
  23.     n += first;
  24.     n += second;
  25.     pthread_mutex_unlock(&mtx);
  26.     printf("On thread %d final the sum was: %d, first was %d, second was %d\n", id, n, first, second);
  27.     return NULL;
  28. }
  29.  
  30.  
  31. int main(){
  32.     pthread_t* tid;
  33.     int size = 1;
  34.     tid = (pthread_t*)malloc(size*sizeof(pthread_t));
  35.     int i = 0;
  36.     while(has_ended == 0){
  37.         //srand(time(NULL));
  38.         int r = rand() % 5;
  39.         pair.first = r;
  40.         r = rand()%5;
  41.         pair.second = r;
  42.         pair.ind = i;
  43.         pthread_create(&tid[i], NULL, count, (void*)&pair);
  44.         i++;
  45.         if(n >= 20){
  46.             has_ended = 1;
  47.         }
  48.         //n += 10;
  49.         size ++;
  50.         tid = (pthread_t*)realloc(tid, size*sizeof(pthread_t));    
  51.     }
  52.     int j;
  53.     for(j = 0; j<i; j++){
  54.         pthread_join(tid[i], NULL);
  55.     }  
  56.     free(tid);
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement