Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/sem.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <dirent.h>
- #include <pthread.h>
- #include <time.h>
- #define EATING 1;
- #define THINKING 2;
- #define HUNGRY 3;
- int phNum = 5;
- int status[5] = {2, 2, 2, 2, 2};
- pthread_mutex_t section;
- void *philosopher(void *arg) {
- int id = arg;
- int left, right;
- switch (id) {
- case 0:
- left = 1;
- right = 4;
- break;
- case 4:
- left = 0;
- right = 3;
- break;
- default:
- right = id - 1;
- left = id + 1;
- break;
- }
- while(1)
- {
- printStat();
- think(id);
- printStat();
- while (status[id] != 1) {
- takeForks(id, left, right);
- }
- printStat();
- eat(id);
- printStat();
- putForks(id);
- }
- pthread_exit(NULL);
- }
- int printStat() {
- int i;
- for (i = 0; i < 5; i++) {
- printf("%ld, ", status[i]);
- }
- printf("\n");
- return 0;
- }
- int think(int id) {
- printf("Phil %ld is thinking\n", id);
- sleep(rand() % phNum + 1);
- status[id] = HUNGRY;
- return 0;
- }
- int eat(int id) {
- printf("Phil %ld is eating\n", id);
- sleep(rand() % phNum + 1);
- return 0;
- }
- int takeForks(int id, int left, int right) {
- pthread_mutex_lock(§ion);
- if ((status[left] != 1) && (status[right] != 1)) {
- printf("Phil %ld got forks \n", id, left, right);
- status[id] = EATING;
- }
- pthread_mutex_unlock(§ion);
- return 0;
- }
- int putForks(int id) {
- printf("Phil %ld has released forks \n", id);
- status[id] = THINKING;
- return 0;
- }
- int main(int argc, char *argv[]) {
- srand (time(NULL));
- int i;
- for (i = 0; i < phNum; i++) {
- pthread_attr_t * thAttr = NULL;
- pthread_t tid;
- pthread_create(&tid, thAttr, philosopher, (void*)i);
- }
- while(1) {}
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement