Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5.  
  6. int gold = 0;
  7. pthread_mutex_t mutex[2];
  8. void *mining()
  9. {
  10.         int times;
  11.         for(times = 0 ; times < 20 ; ++times) {
  12.             pthread_mutex_lock (&mutex[0]);
  13.             gold += 10;
  14.             printf("%dMiner 1 gathered 10 gold\n", times);
  15.             sleep(2);
  16.             pthread_mutex_unlock (&mutex[0]);
  17.         }
  18.     return 0;
  19. }
  20.  
  21. void *sell()
  22. {
  23.     int times;
  24.     for(times = 0 ; times < 20 ; ++times) {
  25.             pthread_mutex_lock (&mutex[1]);
  26.             if(gold < 10)
  27.             {
  28.                 printf("The warehouse is empty, cannot sell!\n");
  29.             }else
  30.             {
  31.                 gold -= 10;
  32.                 printf("Trader 1 sold 10 gold\n");
  33.         sleep(2);
  34.             }
  35.             pthread_mutex_unlock (&mutex[1]);
  36.     }
  37. }
  38. int main ()
  39. {
  40.     pthread_t miner, seller;
  41.    
  42.     pthread_mutex_init(&mutex[0], NULL);
  43.     pthread_create(&miner, NULL, mining, NULL);
  44.     pthread_mutex_init(&mutex[1]);
  45.     pthread_create(&seller, NULL, sell, NULL);
  46.  
  47.     pthread_mutex_destroy(&mutex[0]);
  48.     pthread_mutex_destroy(&mutex[1]);
  49.     pthread_join(miner, NULL);
  50.     pthread_join(seller, NULL);
  51.     printf("Gold: %d", gold);
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement