Matt23

Mutexes zad 1

May 24th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4.  
  5. long counter = 0;
  6. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  7.  
  8. void* incrementCounter(void* iter) {
  9.     for (int i = 0; i < *(int*)iter; i++) {
  10.         // pthread_mutex_lock(&mutex1);
  11.         counter++;
  12.         // pthread_mutex_unlock(&mutex1);
  13.     }
  14. }
  15.  
  16. int main(int argc, char** argv) {
  17.     if (argc != 3) return 1;
  18.  
  19.     int n = atoi(argv[1]);
  20.     int iter = atoi(argv[2]);
  21.  
  22.     pthread_t threads[n];
  23.     for (int i = 0; i < n; i++) {
  24.         pthread_create(&threads[i], NULL, incrementCounter, &iter);
  25.     }
  26.  
  27.     for (int i = 0; i < n; i++) {
  28.         pthread_join(threads[i], NULL);
  29.     }
  30.  
  31.     printf("%ld\n", counter);
  32. }
Advertisement
Add Comment
Please, Sign In to add comment