Advertisement
Cepe6

Untitled

Mar 28th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5.  
  6. int mines_count = 1;
  7. pthread_mutex_t* mines;
  8.  
  9. int total_gold = 0;
  10. int* mines_gold;
  11.  
  12. int gold_avaliable() {
  13. for (int i = 0; i < mines_count; i++) {
  14. if (mines_gold[i] > 0) {
  15. return 1;
  16. }
  17. }
  18. return 0;
  19. }
  20.  
  21. void* gather_gold(void* thread_id) {
  22. long worker_id = (long) thread_id;
  23.  
  24. while(gold_avaliable()) {
  25. for (int i = 0; i < mines_count; i++) {
  26. if (!pthread_mutex_trylock(&mines[i])) {
  27. if(mines_gold[i] >= 10) {
  28. printf("Worker %ld entered mine %d\n", worker_id + 1, i + 1);
  29. total_gold += 10;
  30. mines_gold[i] -= 10;
  31. printf("Worker %ld exited mine %d\n", worker_id + 1, i + 1);
  32. }
  33. if (pthread_mutex_unlock(&mines[i])) {
  34. perror("unlcok");
  35. }
  36. }
  37. }
  38. }
  39.  
  40. return NULL;
  41. }
  42.  
  43. int main(int argc, char** argv) {
  44.  
  45. int workers_count = 2;
  46. int default_mines_gold = 50;
  47.  
  48. if (argc == 4) {
  49. workers_count = atoi(argv[2]);
  50. mines_count = atoi(argv[3]);
  51. default_mines_gold = atoi(argv[1]);
  52. }
  53.  
  54. mines_gold = malloc(sizeof(int) * mines_count);
  55. if (mines_gold == NULL) {
  56. perror("malloc");
  57. }
  58.  
  59. mines = malloc(sizeof(pthread_mutex_t) * mines_count);
  60.  
  61. if (mines == NULL) {
  62. perror("malloc");
  63. }
  64.  
  65. pthread_t workers[workers_count];
  66.  
  67. for (int i = 0; i < mines_count; i++) {
  68. if (pthread_mutex_init(&mines[i], NULL)) {
  69. perror("mutex init");
  70. }
  71. mines_gold[i] = default_mines_gold;
  72. }
  73.  
  74. for (long i = 0; i < workers_count; i++) {
  75. if (pthread_create(&workers[i], NULL, gather_gold, (void*) i)) {
  76. perror("create");
  77. }
  78. }
  79.  
  80. for (long i = 0; i < workers_count; i++) {
  81. if (pthread_join(workers[i], NULL)) {
  82. perror("join");
  83. }
  84. }
  85.  
  86. for (int i = 0; i < mines_count; i++) {
  87. if (!pthread_mutex_destroy(&mines[i])) {
  88. perror("destroy");
  89. }
  90. }
  91. free(mines_gold);
  92. free(mines);
  93.  
  94. printf("All gold %ld, gold collected %ld ", (long)default_mines_gold * mines_count, (long)total_gold);
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement