-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1.cpp
More file actions
76 lines (63 loc) · 2.24 KB
/
problem1.cpp
File metadata and controls
76 lines (63 loc) · 2.24 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
69
70
71
72
73
74
75
76
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <atomic>
class Labyrinth {
private:
std::mutex mtx;
std::condition_variable cv;
bool cupcakeAvailable = true;
int totalGuests;
std::atomic<int> guestsWhoHaveEatenCupcake{0}; // Count of guests who have eaten the cupcake
std::vector<bool> hasVisited; // Track if each guest has visited
std::atomic<bool> allGuestsHaveVisited{false}; // Flag to indicate all guests have visited
public:
Labyrinth(int numGuests) : totalGuests(numGuests), hasVisited(numGuests, false) {}
void enterLabyrinth(int guestId) {
std::unique_lock<std::mutex> lock(mtx);
// Wait until it's this guest's turn or until all guests have visited
cv.wait(lock, [this, guestId]() { return allGuestsHaveVisited || !hasVisited[guestId]; });
if (!cupcakeAvailable) {
// If the cupcake is not available and this guest hasn't eaten, ask for a new one
if (!hasVisited[guestId]) {
cupcakeAvailable = true; // A new cupcake is placed
std::cout << "Guest " << guestId << " asked for a new cupcake.\n";
}
}
if (cupcakeAvailable && !hasVisited[guestId]) {
// If the cupcake is available and this guest hasn't visited, eat the cupcake
cupcakeAvailable = false; // Guest decides to eat the cupcake
guestsWhoHaveEatenCupcake++;
std::cout << "Guest " << guestId << " eats the cupcake.\n";
}
// The leader remembers this guest went in the maze
hasVisited[guestId] = true;
// If this is the counter guest and all guests have eaten the cupcake
if (guestsWhoHaveEatenCupcake == totalGuests) {
//iff all Guests
allGuestsHaveVisited = true;
std::cout << "All guests have visited the labyrinth and eaten the cupcake.\n";
return;
}
cv.notify_all();
}
void startParty() {
std::vector<std::thread> guests;
for (int i = 0; i < totalGuests; ++i) {
guests.emplace_back(&Labyrinth::enterLabyrinth, this, i);
}
for (auto& guest : guests) {
guest.join();
}
}
};
int main() {
int totalGuests;
std::cout << "Enter the number of guests: ";
std::cin >> totalGuests;
Labyrinth labyrinth(totalGuests);
labyrinth.startParty();
return 0;
}