/* * Kitchen.cc * * Multiple chef threads try to access a kitchen object to help with broth * * 1 February 2006 C. Scratchley created to work with QNX 6.3.0 * * Copyright 2006, School of Engineering Science, SFU, Canada * You may modify this software under the terms of the GNU GPL */ #include #include #include #include using namespace std; class brothClass { public: brothClass() { }; void help(char id) { cout << "Chef " << id << " starting to help with broth" << endl; delay(2); cout << "Chef " << id << " finishing helping with broth" << endl; }; }; class kitchenClass { sem_t sem4; brothClass broth; public: kitchenClass() { sem_init(&sem4, 0, 2); // allow 2 chefs in kitchen }; void help(char identifier) { cout << "Chef " << identifier << " asking for permission to help with broth" << endl; sem_wait(&sem4); broth.help(identifier); sem_post(&sem4); }; }; kitchenClass kitchen; void* chef(void* arg) { char identifier = *((char*) arg); int n; for (n = 0; n < 2; n++){ kitchen.help(identifier); delay(1); }; return NULL; }; int main(int argc, char* argv[]) { pthread_t chefA, chefB, chefC; const char A = 'A'; const char B = 'B'; const char C = 'C'; pthread_create( &chefA, NULL, chef, (void*) &A); pthread_create( &chefB, NULL, chef, (void*) &B); pthread_create( &chefC, NULL, chef, (void*) &C); pthread_join(chefA, NULL); pthread_join(chefB, NULL); pthread_join(chefC, NULL); std::cout << "Primary thread ending" << std::endl; return EXIT_SUCCESS; }