C program simulating a three-state traffic light with timed state changes in console, demonstrating basic concurrent programming and timing concepts.
#include <stdio.h>
#include <unistd.h> // for sleep()
// Definition of duration times for each state in seconds
#define DURATA_ROSSO 5
#define DURATA_VERDE 5
#define DURATA_GIALLO 2
int main() {
int stato = 0; // 0=Red, 1=Green, 2=Yellow
while (1) {
switch (stato) {
case 0:
// Red state
printf("Traffic Light: RED\n");
sleep(DURATA_ROSSO); // Waits DURATA_ROSSO seconds
stato = 1; // Switch to Green
break;
case 1:
// Green state
printf("Traffic Light: GREEN\n");
sleep(DURATA_VERDE); // Waits DURATA_VERDE seconds
stato = 2; // Switch to Yellow
break;
case 2:
// Yellow state
printf("Traffic Light: YELLOW\n");
sleep(DURATA_GIALLO); // Waits DURATA_GIALLO seconds
stato = 0; // Return to Red
break;
default:
// Unexpected state, reset to Red
stato = 0;
break;
}
}
return 0; // Not reached
}Software: standard C compiler (gcc, clang, etc.)
Software: standard C library (stdio.h, time.h, unistd.h)
Configuration: no external dependencies required
Hardware: no specific hardware required, runs on console/terminal
Note: the program uses the sleep() function for timing, available on POSIX systems (Linux, macOS). On Windows, adapting the sleep function may be necessary.