Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. #include <unistd.h>
  5. #include <cstdlib>
  6. #include <ctime>
  7.  
  8.  
  9. int gCount = 0;
  10. int sCount = 0;
  11. int customerIDs[100];
  12. bool sandwiches[2];
  13.  
  14. sem_t gLock;
  15. sem_t fLock;
  16.  
  17. std::string randOrder()
  18. {
  19. srand(time(0));
  20. std::string order = "";
  21.  
  22. int randNum = (rand() % 3) + 1;
  23. switch(randNum)
  24. {
  25. case 1: order = "Cheese";
  26. case 2: order = "Ham";
  27. case 3: order = "Ham&Cheese";
  28. }
  29. return order;
  30.  
  31.  
  32. }
  33.  
  34. void *spawnWorkers(void *tid)
  35. {
  36. int id = *((int*)tid);
  37.  
  38. sem_wait(&gLock);
  39. usleep(1000000);
  40. std::cout << "Worker " << id << " spawned " << gCount << std::endl;
  41. gCount++;
  42. usleep(1000000);
  43. if(sCount<2)
  44. {
  45. std::cout << "Worker " << id << " works at station " << sCount << std::endl;
  46. sCount++;
  47. }
  48.  
  49. sem_post(&gLock);
  50.  
  51. sem_wait(&gLock);
  52. for(int s=0; s<sCount; s++)
  53. {
  54. sandwiches[s] = true;
  55. std::cout << "Sandwich ready " << std::endl;
  56. }
  57. sCount--;
  58. sem_post(&gLock);
  59.  
  60. pthread_exit(NULL);
  61.  
  62. }
  63.  
  64.  
  65. void *spawnCustomers(void *tid)
  66. {
  67. int id = *((int*)tid);
  68. int count = 0;
  69. //unsigned int microseconds = 100;
  70. sem_wait(&gLock);
  71. std::cout << "Customer " << id << " stands in line " << gCount << std::endl;
  72. customerIDs[count] = gCount;
  73. count++;
  74. gCount++;
  75. usleep(100009);
  76. sem_post(&gLock);
  77.  
  78. pthread_exit(NULL);
  79. }
  80.  
  81. int main(int argc, const char** argv)
  82. {
  83. sem_init(&gLock, 0, 1);
  84. int count = 0;
  85. pthread_t CustomerThreads[10];
  86. pthread_t WorkerThreads[5];
  87.  
  88. sem_wait(&fLock);
  89. for(int i=0; i<10; i++)
  90. {
  91. int rc = pthread_create(&CustomerThreads[i],NULL,spawnCustomers,(void*)&i);
  92. if(rc)
  93. {
  94. std::cerr << "Unable to spawn thread " << i << std::endl;
  95. exit(-1);
  96. }
  97. }
  98.  
  99. for(int i=0; i<5; i++)
  100. {
  101. int rc = pthread_create(&WorkerThreads[i],NULL,spawnWorkers,(void*)&i);
  102. if(rc)
  103. {
  104. std::cerr << "Unable to spawn thread " << i << std::endl;
  105. exit(-1);
  106. }
  107. }
  108. sem_post(&fLock);
  109. sem_wait(&fLock);
  110. for(int i=0; i<10; i++)
  111. {
  112. std::cout << customerIDs[i] << " ";
  113. }
  114. sem_post(&fLock);
  115.  
  116. //return 0;
  117. pthread_exit(NULL);
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement