Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <dirent.h>
- #include <string.h>
- #include <unistd.h>
- #include <pwd.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/sem.h>
- #include <assert.h>
- #include <time.h>
- #define N 5
- #define LEFT (i - 1) % N
- #define RIGHT (i + 1) % N
- #define THINKING 0
- #define HUNGRY 1
- #define EATING 2
- #define MAX_TIME 5
- int key1, key2;
- typedef int semaphore;
- int state[N];
- semaphore mutex = 1;
- semaphore s[N];
- void down(int semdec)
- {
- struct sembuf semd;
- semd.sem_num = 0;
- semd.sem_op = -1;
- semd.sem_flg = 0;
- semop(semdec, &semd, 1);
- }
- void up(int semdec)
- {
- struct sembuf semd;
- semd.sem_num = 0;
- semd.sem_op = 1;
- semd.sem_flg = 0;
- semop(semdec, &semd, 1);
- }
- void Test(int i){
- if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
- state[i] = EATING;
- up(&s[i]);
- }
- }
- void TakesForks(int i){
- down(&mutex);
- state[i] = HUNGRY;
- Test(i);
- up(&mutex);
- down(&s[i]);
- printf("%d ", i);
- printf("КУШАЕТ\n");
- fflush(stdout);
- }
- void PutForks(int i){
- down(&mutex);
- state[i] = THINKING;
- Test(LEFT);
- Test(RIGHT);
- up(&mutex);
- printf("%d ", i);
- printf("ЧИЛЛИТ\n");
- fflush(stdout);
- }
- void philosopher(int i){
- while(1){
- int th_time = rand() % MAX_TIME;
- sleep(th_time); //размышления
- TakesForks(i);
- int eat_time = rand() % MAX_TIME;
- sleep(eat_time); //кушает
- PutForks(i);
- }
- }
- int main(){
- key1 = ftok("./6tsk.c", 'S');
- int mutex = semget(key1, 0, 0);
- key2 = ftok("./6tsk.c", 'S');
- int s = semget(key2, 2, 0);
- if(fork() == 0){
- philosopher(1);
- }
- if(fork() == 0){
- philosopher(2);
- }
- if(fork() == 0){
- philosopher(3);
- }
- if(fork() == 0){
- philosopher(4);
- }
- if(fork() == 0){
- philosopher(5);
- }
- char c;
- if (c = getchar() == EOF){
- return 0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement