Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4.  
  5. pthread_mutex_t mutex;
  6.  
  7. void* inkrementacja(void* arg_wsk)
  8. {
  9. int* zmienna = (int *) arg_wsk;
  10. for(int i = 0; i < 100000; i++)
  11. {
  12. pthread_mutex_lock(&mutex);
  13. *zmienna+=1;
  14. printf("I: %d\n", *zmienna);
  15. pthread_mutex_unlock(&mutex);
  16. }
  17. return NULL;
  18. }
  19.  
  20. void* dekrementacja(void* arg_wsk)
  21. {
  22. int* zmienna = (int *) arg_wsk;
  23. for(int i = 0; i < 100000; i++)
  24. {
  25. pthread_mutex_lock(&mutex);
  26. *zmienna-=1;
  27. printf("D: %d\n", *zmienna);
  28. pthread_mutex_unlock(&mutex);
  29. }
  30. return NULL;
  31. }
  32.  
  33. int main()
  34. {
  35. pthread_t tid1, tid2;
  36.  
  37. if (pthread_mutex_init(&mutex, NULL) != 0)
  38. {
  39. printf("\n mutex init failed\n");
  40. return 1;
  41. }
  42.  
  43. int zmienna = 0;
  44.  
  45. pthread_create(&tid1, NULL, &dekrementacja, &zmienna);
  46. pthread_create(&tid2, NULL, &inkrementacja, &zmienna);
  47.  
  48. pthread_join(tid1, NULL);
  49. pthread_join(tid2, NULL);
  50. pthread_mutex_destroy(&mutex);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement