Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--------------------------------------------
- // NAME: Veselin Dechev
- // CLASS: XIA
- // NUMBER: 2
- // PROBLEM: #3
- // FILE NAME: Starcraft.c (unix file name)
- // FILE PURPOSE:
- // Synchronising threads with mutex.
- // Example with workers and one mine like THE GAME Starcraft.
- // ...
- //--------------------------------------------
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- int NUM_THREADS; //Number of threads
- pthread_mutex_t lock; //Mutex
- int gold; //Gold in the mine
- int* workers_gold; //gold of every worker
- int startminerals = 0;
- //--------------------------------------------
- // FUNCTION: GetGold
- // Geting the gold from the mine and allows only one worker to work.
- // PARAMETERS:
- // ID of the worker
- //--------------------------------------------
- void* GetGold(void* arg){ //Geting the gold of the mine
- size_t thread_num = (size_t)arg; //get id of the thread
- while(gold>0){ //when there's a gold in mine , loop works
- pthread_mutex_trylock(&lock); //lock mutex
- printf("SCV %zd is mining\n", thread_num);
- if(gold>7){
- gold-=8; //geting the gold
- startminerals = startminerals + 8; //incrments the gold in every worker's inventory
- }
- else{ //if the gold is less than 8 , the worker takes the gold wich lefts.
- startminerals = startminerals + gold;
- gold-=gold;
- }
- printf("SCV %zd is transporting minerals\n", thread_num);
- printf( "SCV %zd delivered minerals to 'Command Center 1' %d\n", thread_num, startminerals);
- printf("Remaining gold: %d\n",gold);
- pthread_mutex_unlock(&lock); //unlock the mutex
- sleep(1); //simulating when the worker works.
- }
- }
- int main(int argc, char* argv[]){ //main
- if(argc<2){ //if there's no arguments
- gold = 5000;
- NUM_THREADS = 5;
- }
- else{ //reading from argument line
- gold = atoi(argv[1]);
- NUM_THREADS = atoi(argv[2]);
- }
- pthread_t threads[NUM_THREADS]; //creating array from threads
- pthread_mutex_init(&lock, NULL); //inits the mutex
- size_t i; //counter
- workers_gold = (int*)malloc(NUM_THREADS*sizeof(int)); // allocate memorry for every worker's inventory
- for (i = 0; i< NUM_THREADS; i++){
- workers_gold[i]=0; //every worker's inventory is set to 0;
- }
- for (i = 1; i <= NUM_THREADS; i++) {
- int error = pthread_create(&threads[i], NULL, GetGold, (void*)i); //creating the threads and checks for errors.
- if (error != 0) {
- fprintf(stderr, "Error creating thread %zd: error: %d\n", i, error);
- }
- }
- for (i = 0; i < NUM_THREADS; i++) {
- int error = pthread_join(threads[i], NULL); //joining the threads.
- if (error != 0) {
- fprintf(stderr, "Error joining thread %zd: error: %d\n", i, error);
- }
- }
- pthread_mutex_destroy(&lock); //destroys mutex
- pthread_exit(NULL); //exit from the threads
- return 0; //epic crash!!!
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement