Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<pthread.h>
  4.  
  5. int global_variable;
  6.  
  7. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  8.  
  9. void * change_value(void * arg)
  10. {
  11. int operation = (int) arg, i;
  12. for (i = 0; i < 100000; i++)
  13. {
  14. pthread_mutex_lock(&mutex);
  15. if (operation == 0)
  16. {
  17. global_variable++;
  18. }
  19. else
  20. {
  21. global_variable--;
  22. }
  23. pthread_mutex_unlock(&mutex);
  24. printf("%d ", global_variable);
  25. fflush(stdout);
  26. }
  27. }
  28.  
  29. int main()
  30. {
  31. printf("Hello \n");
  32. pthread_t addition, substraction;
  33. pthread_create(&addition, NULL, change_value, (void *) 0);
  34. pthread_create(&substraction, NULL, change_value, (void*) 1);
  35. pthread_join(addition, NULL);
  36. pthread_join(substraction, NULL);
  37. pthread_exit(NULL);
  38.  
  39. return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement