-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem2.cpp
More file actions
68 lines (56 loc) · 1.88 KB
/
problem2.cpp
File metadata and controls
68 lines (56 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
// This uses the third method on here, where all the guests are in line
class Showroom{
private:
std::mutex mtx;
std::condition_variable cv;
std::queue<int> queue; // Queue to manage guest turns
bool showroomAvailable = true; // Initially, the showroom is available
int totalGuests; // Example total number of guests
std::vector<std::thread> guests;
public:
Showroom(int totalGuests) : totalGuests(totalGuests) {}
void visitShowroom(int guestId) {
{
std::unique_lock<std::mutex> lock(mtx); //locks the mutex thread
queue.push(guestId); // Guest gets in line
while (queue.front() != guestId || !showroomAvailable) { // Wait for turn and availability
cv.wait(lock);
}
//once it's the guests turn they can enter the showroom
showroomAvailable = false;
}
//problem simulation
std::cout << "Guest " << guestId << " is viewing the vase." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Guest " << guestId << " has finished viewing the vase." << std::endl;
{
std::unique_lock<std::mutex> lock(mtx); //locks the thread until they're removed from queue
showroomAvailable = true;
queue.pop(); // Remove guest from the queue
}
cv.notify_one(); // Notify the next guest
}
void startParty() {
std::vector<std::thread> guests;
for (int i = 0; i < totalGuests; ++i) {
guests.emplace_back(&Showroom::visitShowroom, this, i);
}
for (auto& guest : guests) {
guest.join();
}
std::cout << "All guests have viewed the vase." << std::endl;
}
};
int main() {
int totalGuests;
std::cout << "Enter the number of guests: ";
std::cin >> totalGuests;
Showroom showroom(totalGuests);
showroom.startParty();
return 0;
}