In this assignment you will explore concurrency and semaphores by writing a C console program that runs several different threads. Your concurrent threads must use semaphores to coordinate the resrouces in a simple bakery shop with the following characteriscs:
Your code must be written in C (not C++).
In your program, each customer is represented by a unique thread. The baker is represented by two threads -- one thread for when the baker is baking a loaf of bread, and one thread for when the baker is acting as the cashier. The pthread library must be used for creating and exiting threads.
Coordination between threads must be done with counting semaphores, the API being defined in
The main program does this:
pthread_exit(NULL);so that the main program does not exit until all the threads have exited.
The output from your main code and the threads must be comprised of a series of messages as each thread progresses. Precde each output message with a brief identifier to indicate which thread (cash register, bread baking, or customer along with the customer number) display each message. A short message should be displayed when each of the following events occur:
fprintf(stderr, ...) to print messages, as
stderr is not buffered output and thus will appear on your terminal screen "as soon as" the call is done.
From the semaphore library, you need to use only 3 functions:
Note: if no delays are introduced in the code, some threads may terminate before others even get a chance to start. In order to better interleave the execution of the threads, sprinkle delays throughout your code using the
usleep() function. At a minimum, introduce one second delays in each of the following operations:
Although the pthreads library is generally available for all common OSes, I found that when I ran my code on MacOS, it did not work, but when I tried it on Linux, it was fine. So, while you might make some good progress working on your desktop/laptop machine, make sure your code runs correctly on the Ubuntu machines in the Ulab.
Also, don't forget that you have to link your code with the pthread library. So, when compiling, you need to specify
-lpthread to gcc. E.g.,
gcc bakeshop.c -o bakeshop -lpthread
Run the program several times and answer the following questions:
/home/cs/232/current/<yourid>/proj4 1) your code, 2) a typescript file showing the output from two runs of your code, and 3) a text file answering the two above questions.
Due date: Wednesday, April 5, at 11:59 pm.
Calvin > CS > 232 > Projects > 4