# Traffic Control Problem

`NS-cars.c` and `EW-cars.c` are two programs that simulate traffic control. When north-south cars pass the crossroads, they should ensure that road from north to south is available, if north-south road is not available, they keep waiting. This is the same to east-west cars. Note that when north-south road is available, east-west road is not available and vice versa.

Please add **semaphore synchronization** in these two programs so that north-south cars and east-west cars can pass the crossroads alternately and there will not be car accident.

```c
/*NS-cars.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
    int i, car = 0, loop = 3;
    for (i = 0; i < loop; i++) {
        printf("Semaphore: The road from north to south is open\n");
        sleep(1);
        printf("NS-Car: car %d passed\n", car++);
    }
    printf("NS: Time is up. %d cars passed.\n", car);
    return 0;
}
```

```c
/*EW-cars.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
    int i, car = 0, loop = 3;
    for (i = 0; i < loop; i++) {
        printf("Semaphore: The road from east to west is open\n");
        sleep(rand() % 2 + 1);
        printf("EW-Car: car %d passed\n", car++);
    }
    printf("EW: Time is up. %d cars passed.\n", car);
    return 0;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://eric-lo.gitbook.io/synchronization/traffic-control-problem.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
