Skip to content

Commit 5dea38a

Browse files
authored
Create traffic-light-controlled-intersection.cpp
1 parent 2edd053 commit 5dea38a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class TrafficLight {
5+
public:
6+
TrafficLight()
7+
: light_{1} {
8+
9+
}
10+
11+
void carArrived(
12+
int carId, // ID of the car
13+
int roadId, // ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
14+
int direction, // Direction of the car
15+
function<void()> turnGreen, // Use turnGreen() to turn light to green on current road
16+
function<void()> crossCar // Use crossCar() to make car cross the intersection
17+
) {
18+
unique_lock<mutex> lock{m_};
19+
if (light_ != roadId) {
20+
light_ = roadId;
21+
turnGreen();
22+
}
23+
crossCar();
24+
}
25+
26+
private:
27+
mutex m_;
28+
int light_;
29+
};

0 commit comments

Comments
 (0)