Unix Programming - Re: how to solve the philosopher problem .and what's wrong with my

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > September 2006 > Re: how to solve the philosopher problem .and what's wrong with my





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Re: how to solve the philosopher problem .and what's wrong with my
Renato Golin

2006-09-28, 1:20 pm

Aggelos Mpimpoudis wrote:
> But what about DaVinci? Did he managed to settle the pholosophers to eat
> (or I said something wrong at my reply earlier and he gave up :O ???)


Ah, good point, I almost forgot of that. I could make his code work with
your advice and by putting the pthread_join later (otherwise it just sat
and waited). And btw, I put (i--) on phlosi so it won't go forever... ;)

Here's my full code:


#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 5
#define LEFT (i+NUM-1)%NUM
#define RIGHT (i+1)%NUM
#define FREE 0
#define USED 1

struct Fork
{
int flag;
int num;
};
static struct Fork *forks[NUM];

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_t tid[NUM];

void
getting (int i)
{
pthread_mutex_lock (&lock);

if (forks[LEFT]->flag == FREE)
{
forks[LEFT]->flag = USED;
printf ("pholos%d picking fork %d\n", i, LEFT);
}
if (forks[RIGHT]->flag == FREE)
{
forks[RIGHT]->flag = USED;
printf ("pholos%d picking fork %d\n", i, RIGHT);
}
pthread_mutex_unlock (&lock);
return;

}

void
putting (int i)
{
pthread_mutex_lock (&lock);
forks[LEFT]->flag = FREE;
printf ("phlosi%d putting fork%d\n", i, LEFT);
pthread_mutex_unlock (&lock);

pthread_mutex_lock (&lock);
forks[RIGHT]->flag = FREE;
printf ("phlosi%d putting fork%d\n", i, RIGHT);
pthread_mutex_unlock (&lock);

}

void
thinking (int i)
{
printf ("phlosi%d is thingking\n", i);
sleep(1);
}

void
eatting (int i)
{
printf ("phlosi%d is eatting\n", i);
}

void
phlosi (int i)
{
while (i--)
{
thinking (i);
getting (i);
eatting (i);
putting (i);
}
}

int
main ()
{
int i=0, ret=0;

for (i=0; i<NUM; i++)
{
forks[i] = (struct Fork *) malloc (sizeof (struct Fork));
forks[i]->flag = FREE;
forks[i]->num = i;
}

for (i=0; i<NUM; i++)
{
ret = pthread_create (tid+i, NULL, (void *) phlosi, (void *) i);
if (ret)
return ret;
}

for (i=0; i<NUM; i++)
{
pthread_join(tid[i], NULL);
}
return 0;
}
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com