#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//#include <unistd.h>
#ifndef __linux
#include <windows.h>
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H */
#else
#include <unistd.h>
#endif /*__linux*/
//end unistd.h
void * ph1(void * chop)
{
int n = 0;
while (n < 10)
{
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[0]);
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[1]);
printf("Philosopher 0 is eating.\n");
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[1]);
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[0]);
printf("Philosopher 0 is thinking.\n\n");
n++;
sleep(0.5);//sleep(0.5);
};
return 0;
}
void * ph2(void * chop)
{
int n = 0;
while (n < 10)
{
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[1]);
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[2]);
printf("Philosopher 1 is eating.\n");
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[2]);
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[1]);
printf("Philosopher 1 is thinking.\n\n");
n++;
sleep(0.5);//sleep(0.5);
};
return 0;
}
void * ph3(void * chop)
{
int n = 0;
while (n < 10)
{
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[2]);
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[3]);
printf("Philosopher 2 is eating.\n");
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[3]);
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[2]);
printf("Philosopher 2 is thinking.\n\n");
n++;
sleep(0.5);//sleep(0.5);
};
return 0;
}
void * ph4(void * chop)
{
int n = 0;
while (n < 10)
{
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[3]);
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[4]);
printf("Philosopher 3 is eating.\n");
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[4]);
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[3]);
printf("Philosopher 3 is thinking.\n\n");
n++;
sleep(0.5);//sleep(0.5);
};
return 0;
}
void * ph5(void * chop)
{
int n = 0;
while (n < 10)
{
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[0]);
pthread_mutex_trylock(&((pthread_mutex_t *)chop)[4]);
printf("Philosopher 4 is eating.\n");
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[4]);
pthread_mutex_unlock(&((pthread_mutex_t *)chop)[0]);
printf("Philosopher 4 is thinking.\n\n");
n++;
sleep(0.5);//sleep(0.5);
};
return 0;
}
int main(void)
{
pthread_t ptid1, ptid2, ptid3, ptid4, ptid5;
pthread_mutex_t chop[5];
int i = 0;
for (i = 0; i < 5; i++)
pthread_mutex_init(&chop[i], NULL);
pthread_create(&ptid1, NULL, ph1, chop);
pthread_create(&ptid2, NULL, ph2, chop);
pthread_create(&ptid3, NULL, ph3, chop);
pthread_create(&ptid4, NULL, ph4, chop);
pthread_create(&ptid5, NULL, ph5, chop);
pthread_join(ptid1, NULL);
pthread_join(ptid2, NULL);
pthread_join(ptid3, NULL);
pthread_join(ptid4, NULL);
pthread_join(ptid5, NULL);
for (i = 0; i < 5; i++)
pthread_mutex_destroy(&chop[i]);
return 0;
}