Some background:
I have a c++ program that is multithreaded using pthreads. The program is a hotel reservation system, with 10 guests (each their own thread), a check-in desk (1 thread) and a check-out desk (1 thread). There are only 5 rooms in the hotel that a guest can be in. I am using semaphores to enforce mutual exclusion and event ordering in this program.
Question:
here is my code (Just parts that are needed...)
sem_init(&openRooms, 0, 5);
sem_wait(&openRooms); //waits for there to be an open room at the hotel
cout << "Guest " << guestNumber << " waits for check-in." << endl;
sem_wait(&checkInLine); //waits for an open spot at the check-in desk
There are 5 guests that are able to be in the hotel at a time, because there are 5 rooms. When I run the program, I get the output (or something like...)
Guest Guest Guest Guest 24 waits for check-in. waits for check-in.1 waits for check-in.
3 waits for check-in.
It seems that cout is letting multiple prints be run at the same time, which is why "Guest" is printed multiple times in a row.
I have tried doing this with printf, and the same issue doesn't happen. The entire statement is printed before another thread can print the statement.
sem_wait(&checkInSt); //Only one person at check in receptionist at a time
printf("Guest %ld goes to the check-in receptionist.\n", my_rank);
currentThreadIn = my_rank; //Rank for receptionist to use in room assignment
Output:
Guest 1 waits for check in.
Guest 3 waits for check in.
Guest 2 waits for check in.
Guest 4 waits for check in.
Guest 0 waits for check in.
Why does this happen? Is there some sort of bugger that cout uses? Additionally, is there any way to avoid this using cout? I could use an additional semaphore to ensure that the cout statement prints before another can print, but I'm looking for a way without using that additional semaphore