Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<string.h>
- #include<pthread.h>
- #include<stdlib.h>
- #include<unistd.h>
- int counter;
- int gold = 0;
- pthread_mutex_t lock;
- int minegold = 50;
- void* Mine(void *arg)
- {
- long id = (long) arg;
- int i=0;
- for(; minegold >= 0; minegold-=10){
- pthread_mutex_trylock(&lock);
- if(minegold <= 0){
- break;
- }
- gold+=10;
- printf("Miner %ld gathered 10 gold from Mine 1 \n",id + 1);
- pthread_mutex_unlock(&lock);
- sleep(1);
- }
- return NULL;
- }
- int main(int argc, char* argv[])
- {
- int num1;
- int num2;
- pthread_t* miner;
- pthread_t* seller;
- if(argc == 3){
- int i = 0;
- int *index = NULL;
- if (argv[1])
- num1 = atoi(argv[1]);
- index = calloc (num1, sizeof (int));
- for(i = 0; i < num1; i++)
- {
- index[i] = i;
- }
- miner = malloc(sizeof(pthread_t)*num1);
- i = 0;
- if (argv[2])
- num2 = atoi(argv[2]);
- index = calloc (num2, sizeof (int));
- for(i = 0; i < num2; i++)
- {
- index[i] = i;
- }
- seller = malloc(sizeof(pthread_t)*num2);
- }
- else{
- int i = 0;
- int *index = NULL;
- num1=num2 = 2;
- index = calloc (num1, sizeof (int));
- for(i = 0; i < num1; i++)
- {
- index[i] = i;
- }
- miner = malloc(sizeof(pthread_t)*num1);
- /*
- i = 0;
- index = calloc (num2, sizeof (int));
- for(i = 0; i < num2; i++)
- {
- index[i] = i;
- }
- seller = malloc(sizeof(pthread_t)*num2);
- */
- }
- // argv[2] miner
- // argv[3] seller
- long i = 0;
- int err;
- if (pthread_mutex_init(&lock, NULL) != 0)
- {
- printf("\n mutex init failed\n");
- return 1;
- }
- for( i = 0; i < num1; i++){
- err = pthread_create(&(miner[i]), NULL, &Mine, (void*) i);
- if (err != 0)
- printf("\ncan't create thread :[%s]", strerror(err));
- }
- /*
- for( i = 0; i < num2; i++){
- err = pthread_create(&(seller[i]), NULL, &Sell, (void*) i);
- if (err != 0)
- printf("\ncan't create thread :[%s]", strerror(err));
- }
- */
- for( i =0 ;i < num1; i++)
- pthread_join(miner[i], NULL);
- /*
- for( i =0 ;i < num2; i++)
- pthread_join(seller[i], NULL);
- */
- pthread_mutex_destroy(&lock);
- printf("Gold: %d\n",gold);
- free(miner);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement