Advertisement
Guest User

Untitled

a guest
Jul 28th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5.  
  6. int gold_total;
  7. pthread_mutex_t Mutex;
  8.  
  9. void* mine(void* argument){
  10. int arg = (int)argument;
  11. int my_value = 0;
  12. while(1){
  13. sleep(1);
  14. pthread_mutex_lock(&Mutex);
  15. printf("Worker number %d is mining!\n",arg);
  16. if (gold_total == 0){
  17. pthread_mutex_unlock(&Mutex);
  18. pthread_exit((void *)my_value);
  19. }
  20. my_value += 10;
  21. gold_total -= 10;
  22. pthread_mutex_unlock(&Mutex);
  23. }
  24. }
  25.  
  26.  
  27. int main(int argc, char** argv){
  28. int i;
  29. int a[2];
  30. pthread_mutex_init(&Mutex, NULL);
  31.  
  32. for (i = 1; i < argc; i++){
  33. a[i-1] = atoi(argv[i]);
  34. }
  35.  
  36. pthread_t Workers[a[1]];
  37. gold_total = a[0];
  38. int gold[a[1]];
  39. int return_gold[a[1]];
  40.  
  41. for (i = 0; i < a[1];i++){
  42. pthread_create(&Workers[i], NULL, mine,(void *) i+1);
  43. }
  44.  
  45. for (i = 0; i < a[1];i++){
  46. pthread_join(Workers[i],(void **)&gold[i]);
  47. return_gold[i] = (int) gold[i];
  48. printf("%d\n", return_gold[i]);
  49. }
  50.  
  51. pthread_mutex_destroy(&Mutex);
  52.  
  53. return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement