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_total;
- pthread_mutex_t Mutex;
- void* mine(void* argument){
- int arg = (int)argument;
- int my_value = 0;
- while(1){
- sleep(1);
- pthread_mutex_lock(&Mutex);
- printf("Worker number %d is mining!\n",arg);
- if (gold_total == 0){
- pthread_mutex_unlock(&Mutex);
- pthread_exit((void *)my_value);
- }
- my_value += 10;
- gold_total -= 10;
- pthread_mutex_unlock(&Mutex);
- }
- }
- int main(int argc, char** argv){
- int i;
- int a[2];
- pthread_mutex_init(&Mutex, NULL);
- for (i = 1; i < argc; i++){
- a[i-1] = atoi(argv[i]);
- }
- pthread_t Workers[a[1]];
- gold_total = a[0];
- int gold[a[1]];
- int return_gold[a[1]];
- for (i = 0; i < a[1];i++){
- pthread_create(&Workers[i], NULL, mine,(void *) i+1);
- }
- for (i = 0; i < a[1];i++){
- pthread_join(Workers[i],(void **)&gold[i]);
- return_gold[i] = (int) gold[i];
- printf("%d\n", return_gold[i]);
- }
- pthread_mutex_destroy(&Mutex);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement