Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <unistd.h>
- #include <semaphore.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/sem.h>
- #include <signal.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <string.h>
- #define N 10
- #define limit 5
- #define wait 10
- #define lenght 5
- //sem_t lightLeft, lightRight;
- sem_t lights[2];
- //int carsLeft=0, carsRight=0;
- sem_t road, change;
- int side=0;
- char dir[2][6] = {"left", "right"};
- struct car_info
- {
- int way;
- int id;
- };
- void * timerf()
- {
- printf("Timer start\n");
- int waitingtime = wait + rand()%wait;
- while (1)
- {
- sleep(waitingtime);
- side=(side+1)%2;
- sem_post(&change);
- printf("Prosba o zmiane swiatel wyslana\n");
- }
- }
- void * car (void *arg)
- {
- struct car_info *info = arg;
- int tid = info->way;
- int id = info->id;
- while (1)
- {
- printf("Auto stoi w kolejce [%d][%s]\n",id, dir[tid]);
- sem_wait(&road);
- sem_post(&road);
- printf("Auto czeka za swiatlami [%d][%s]\n",id, dir[tid]);
- sem_wait(&lights[tid]);
- printf ("Auto wjezdza na droge [%d][%s]\n",id, dir[tid]);
- sleep(lenght + rand()%lenght);
- printf("Auto wyjezdza z drogi [%d][%s]\n",id, dir[tid]);
- sem_post(&lights[tid]);
- tid = (tid+1)%2;
- sleep(lenght + rand()%lenght);
- }
- }
- void * signalsystem()
- {
- int i=0;
- int now=side;
- //int carsRoad=5;
- while (1)
- {
- printf("Swiatla zielone [%s]\n", dir[now]);
- for (i=0;i<limit;i++)
- sem_post(&lights[now]);
- sem_post(&road);
- //sem_post(&lights[now]);
- sem_wait(&change);
- printf("Prosba o zmiane swiatel otrzymana\n");
- sem_wait(&road);
- printf("Swiatla czerwone [%s]\n", dir[now]);
- for (i=0;i<limit;i++)
- sem_wait(&lights[now]);
- printf("Droga pusta\n");
- now=side;
- }
- }
- void addCar(pthread_t thread, struct car_info info)
- {
- pthread_create(&thread, NULL, &car, &info);
- }
- int main()
- {
- pthread_t thread_id[N], timer;
- //init
- sem_init(&lights[0], 0, 0);
- sem_init(&lights[1], 0, 0);
- sem_init(&road, 0, 0);
- sem_init(&change, 0, 0);
- int carAmount=1;
- char temp;
- int continious=1;
- //petla glowna programu
- pthread_create(&thread_id[0], NULL,
- &signalsystem, NULL);
- pthread_create(&timer, NULL,
- &timerf, NULL);
- while (continious)
- {
- scanf("%c", &temp);
- switch(temp)
- {
- case 'l':
- ;
- struct car_info infol = {0, carAmount};
- addCar(thread_id[carAmount++], infol);
- break;
- case 'r':
- ;
- struct car_info infor = {1, carAmount};
- addCar(thread_id[carAmount++], infor);
- break;
- case 'e':
- continious=0;
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement