Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <semaphore.h>
- #define THINKING 0
- #define HUNGRY 1
- #define EATING 2
- #define LEFT (i-1)%N
- #define RIGHT (i+1)%N
- typedef int semaphore;
- int N=5;
- int status [5];
- semaphore mutex = 1;
- semaphore s[5];
- void PrintStatus()
- {
- int i;
- for (i=0; i<N; i++)
- printf ("Состояние ",i, " философа - ", status[i]);
- }
- void Test(int i)
- {
- if(status[i]==HUNGRY && status[LEFT]!=EATING && status[RIGHT]!=EATING)
- {
- status[i] = EATING;
- up(&s[i]);
- }
- }
- void TakeForks(int i)
- {
- down(&mutex);
- status[i] = HUNGRY;
- PrintStatus();
- Test(i);
- up(&mutex);
- down(&s[i]);
- }
- void PutForks(int i)
- {
- down(&mutex);
- status[i] = THINKING;
- PrintStatus();
- Test(LEFT);
- Test(RIGHT);
- up(&mutex);
- }
- void Eat (int i)
- {
- printf ("Философ ", i, " ест.");
- }
- void Philosopher(void* j)
- {
- int i = *(int*)j;
- int k = 0;
- while(k<10)
- {
- TakeForks(i);
- Eat(i);
- PutForks(i);
- k++;
- }
- }
- int main ()
- {
- pthread_t thread[N];
- int i, ithread;
- for (i=0; i<N; i++)
- status[i] = THINKING;
- for (i=0; i<N; i++)
- {
- ithread = pthread_create (&thread[i], NULL, (void *(*)(void *))Philosopher, &i);
- if (ithread != 0)
- {
- printf ("Error 2");
- return 1;
- }
- }
- for (i=0; i<N; i++)
- {
- ithread = pthread_join(thread[i], NULL);
- if (ithread != 0)
- {
- printf ("Error 3");
- return 1;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement