Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <pthread.h>
- #include <semaphore.h>
- #include <unistd.h>
- #include <cstdlib>
- #include <ctime>
- int gCount = 0;
- int sCount = 0;
- int customerIDs[100];
- bool sandwiches[2];
- sem_t gLock;
- sem_t fLock;
- std::string randOrder()
- {
- srand(time(0));
- std::string order = "";
- int randNum = (rand() % 3) + 1;
- switch(randNum)
- {
- case 1: order = "Cheese";
- case 2: order = "Ham";
- case 3: order = "Ham&Cheese";
- }
- return order;
- }
- void *spawnWorkers(void *tid)
- {
- int id = *((int*)tid);
- sem_wait(&gLock);
- usleep(1000000);
- std::cout << "Worker " << id << " spawned " << gCount << std::endl;
- gCount++;
- usleep(1000000);
- if(sCount<2)
- {
- std::cout << "Worker " << id << " works at station " << sCount << std::endl;
- sCount++;
- }
- sem_post(&gLock);
- sem_wait(&gLock);
- for(int s=0; s<sCount; s++)
- {
- sandwiches[s] = true;
- std::cout << "Sandwich ready " << std::endl;
- }
- sCount--;
- sem_post(&gLock);
- pthread_exit(NULL);
- }
- void *spawnCustomers(void *tid)
- {
- int id = *((int*)tid);
- int count = 0;
- //unsigned int microseconds = 100;
- sem_wait(&gLock);
- std::cout << "Customer " << id << " stands in line " << gCount << std::endl;
- customerIDs[count] = gCount;
- count++;
- gCount++;
- usleep(100009);
- sem_post(&gLock);
- pthread_exit(NULL);
- }
- int main(int argc, const char** argv)
- {
- sem_init(&gLock, 0, 1);
- int count = 0;
- pthread_t CustomerThreads[10];
- pthread_t WorkerThreads[5];
- sem_wait(&fLock);
- for(int i=0; i<10; i++)
- {
- int rc = pthread_create(&CustomerThreads[i],NULL,spawnCustomers,(void*)&i);
- if(rc)
- {
- std::cerr << "Unable to spawn thread " << i << std::endl;
- exit(-1);
- }
- }
- for(int i=0; i<5; i++)
- {
- int rc = pthread_create(&WorkerThreads[i],NULL,spawnWorkers,(void*)&i);
- if(rc)
- {
- std::cerr << "Unable to spawn thread " << i << std::endl;
- exit(-1);
- }
- }
- sem_post(&fLock);
- sem_wait(&fLock);
- for(int i=0; i<10; i++)
- {
- std::cout << customerIDs[i] << " ";
- }
- sem_post(&fLock);
- //return 0;
- pthread_exit(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement