Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <stdlib.h>
- int mines_count = 1;
- pthread_mutex_t* mines;
- int total_gold = 0;
- int* mines_gold;
- int gold_avaliable() {
- for (int i = 0; i < mines_count; i++) {
- if (mines_gold[i] > 0) {
- return 1;
- }
- }
- return 0;
- }
- void* gather_gold(void* thread_id) {
- long worker_id = (long) thread_id;
- while(gold_avaliable()) {
- for (int i = 0; i < mines_count; i++) {
- if (!pthread_mutex_trylock(&mines[i])) {
- if(mines_gold[i] >= 10) {
- printf("Worker %ld entered mine %d\n", worker_id + 1, i + 1);
- total_gold += 10;
- mines_gold[i] -= 10;
- printf("Worker %ld exited mine %d\n", worker_id + 1, i + 1);
- }
- if (pthread_mutex_unlock(&mines[i])) {
- perror("unlcok");
- }
- }
- }
- }
- return NULL;
- }
- int main(int argc, char** argv) {
- int workers_count = 2;
- int default_mines_gold = 50;
- if (argc == 4) {
- workers_count = atoi(argv[2]);
- mines_count = atoi(argv[3]);
- default_mines_gold = atoi(argv[1]);
- }
- mines_gold = malloc(sizeof(int) * mines_count);
- if (mines_gold == NULL) {
- perror("malloc");
- }
- mines = malloc(sizeof(pthread_mutex_t) * mines_count);
- if (mines == NULL) {
- perror("malloc");
- }
- pthread_t workers[workers_count];
- for (int i = 0; i < mines_count; i++) {
- if (pthread_mutex_init(&mines[i], NULL)) {
- perror("mutex init");
- }
- mines_gold[i] = default_mines_gold;
- }
- for (long i = 0; i < workers_count; i++) {
- if (pthread_create(&workers[i], NULL, gather_gold, (void*) i)) {
- perror("create");
- }
- }
- for (long i = 0; i < workers_count; i++) {
- if (pthread_join(workers[i], NULL)) {
- perror("join");
- }
- }
- for (int i = 0; i < mines_count; i++) {
- if (!pthread_mutex_destroy(&mines[i])) {
- perror("destroy");
- }
- }
- free(mines_gold);
- free(mines);
- printf("All gold %ld, gold collected %ld ", (long)default_mines_gold * mines_count, (long)total_gold);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement