Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- #include <unistd.h>
- int gold = 0;
- pthread_mutex_t mutex[2];
- void *mining()
- {
- int times;
- for(times = 0 ; times < 20 ; ++times) {
- pthread_mutex_lock (&mutex[0]);
- gold += 10;
- printf("%dMiner 1 gathered 10 gold\n", times);
- sleep(2);
- pthread_mutex_unlock (&mutex[0]);
- }
- return 0;
- }
- void *sell()
- {
- int times;
- for(times = 0 ; times < 20 ; ++times) {
- pthread_mutex_lock (&mutex[1]);
- if(gold < 10)
- {
- printf("The warehouse is empty, cannot sell!\n");
- }else
- {
- gold -= 10;
- printf("Trader 1 sold 10 gold\n");
- sleep(2);
- }
- pthread_mutex_unlock (&mutex[1]);
- }
- }
- int main ()
- {
- pthread_t miner, seller;
- pthread_mutex_init(&mutex[0], NULL);
- pthread_create(&miner, NULL, mining, NULL);
- pthread_mutex_init(&mutex[1]);
- pthread_create(&seller, NULL, sell, NULL);
- pthread_mutex_destroy(&mutex[0]);
- pthread_mutex_destroy(&mutex[1]);
- pthread_join(miner, NULL);
- pthread_join(seller, NULL);
- printf("Gold: %d", gold);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement