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 |
#include <iostream> #include <chrono> #include <thread> // Constants for traffic light durations const int GREEN_DURATION = 10; // Duration of green light in seconds const int YELLOW_DURATION = 3; // Duration of yellow light in seconds const int RED_DURATION = 7; // Duration of red light in seconds // Function to simulate traffic signal control void simulateTrafficSignal() { while (true) { std::cout << "Green light\n"; std::this_thread::sleep_for(std::chrono::seconds(GREEN_DURATION)); std::cout << "Yellow light\n"; std::this_thread::sleep_for(std::chrono::seconds(YELLOW_DURATION)); std::cout << "Red light\n"; std::this_thread::sleep_for(std::chrono::seconds(RED_DURATION)); } } int main() { std::cout << "Traffic Signal Control Simulation\n"; simulateTrafficSignal(); return 0; } |
Explanation
- Constants:
GREEN_DURATION
: The duration of the green light phase in seconds.YELLOW_DURATION
: The duration of the yellow light phase in seconds.RED_DURATION
: The duration of the red light phase in seconds.
- simulateTrafficSignal Function:
- Continuously simulates the traffic signal cycles.
- Green Light: Prints “Green light” and waits for
GREEN_DURATION
seconds. - Yellow Light: Prints “Yellow light” and waits for
YELLOW_DURATION
seconds. - Red Light: Prints “Red light” and waits for
RED_DURATION
seconds. - The cycle repeats indefinitely.
- Main Function:
- Displays a message indicating the start of the traffic signal control simulation.
- Calls
simulateTrafficSignal
to start the simulation.
Usage
- Traffic Light Phases: The program cycles through green, yellow, and red light phases, simulating a traffic signal’s operation.
- Duration: Adjust the
GREEN_DURATION
,YELLOW_DURATION
, andRED_DURATION
constants to change the timing of each phase.