Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. int currentBalance=100,newBalance=0,oldBalance=0;
  4. pthread_mutex_t mutex;
  5.  
  6. void* thread1(){
  7. pthread_mutex_lock(&mutex);
  8. oldBalance = currentBalance;
  9. newBalance = oldBalance + 10000;
  10. currentBalance = newBalance;
  11. pthread_mutex_unlock(&mutex);
  12. }
  13.  
  14. void* thread2(){
  15. pthread_mutex_lock(&mutex);
  16. oldBalance = currentBalance;
  17. newBalance = oldBalance + 5000;
  18. currentBalance = newBalance;
  19. pthread_mutex_unlock(&mutex);
  20. }
  21.  
  22. void* thread3(){
  23. pthread_mutex_lock(&mutex);
  24. currentBalance = currentBalance;
  25. newBalance = oldBalance + 5500;
  26. currentBalance = currentBalance;
  27. pthread_mutex_unlock(&mutex);
  28. }
  29.  
  30. int main()
  31. {
  32. pthread_t trd1,trd2,trd3;
  33. pthread_attr_t attr;
  34. pthread_mutex_init(&mutex,NULL);
  35. pthread_attr_init(&attr);
  36. pthread_create(&trd1,NULL,thread1,NULL);
  37. pthread_join(trd1,NULL);
  38. pthread_create(&trd2,NULL,thread2,NULL);
  39. pthread_join(trd2,NULL);
  40. pthread_create(&trd3,NULL,thread3,NULL);
  41. pthread_join(trd3,NULL);
  42. printf("Current Balance: %dn",currentBalance);
  43. return 0;
  44. }
  45.  
  46. gcc -pthread task6.c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement