Line 1: Line 1:
 +
<metadesc>C implementation of dining philosophers problem with threads</metadesc>
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
 
//Dining philosopher using threads
 
//Dining philosopher using threads

Revision as of 15:47, 1 December 2013

<syntaxhighlight lang="c"> //Dining philosopher using threads

  1. include<stdio.h>
  2. include<pthread.h>

void* reader(void*); pthread_mutex_t mut[5]; int n;

int main() {

 pthread_t t1[5];
 int i,j=0,k;
 n = 5;
 for(i=0;i<n;i++)
   {
     j=i;
     pthread_create(&t1[i],NULL,reader,&j);
   }
 for(j=0;j<n;j++)
   pthread_join(t1[j],NULL);
 return 1;

}

void *reader(void* arg) {

 int val=*(int*)arg;
 printf("%d Thinking\n",val+1);
 pthread_mutex_lock(&mut[val%n]);
 pthread_mutex_lock(&mut[(val+1)%n]);
 printf("%d Eating\n",val+1);
 sleep(3);
 pthread_mutex_unlock(&mut[val%n]);
 pthread_mutex_unlock(&mut[(val+1)%n]);
 printf("%d Finished Eating\n",val+1);

} </syntaxhighlight>



<syntaxhighlight lang="c"> //Dining philosopher using threads

  1. include<stdio.h>
  2. include<pthread.h>

void* reader(void*); pthread_mutex_t mut[5]; int n;

int main() {

 pthread_t t1[5];
 int i,j=0,k;
 n = 5;
 for(i=0;i<n;i++)
   {
     j=i;
     pthread_create(&t1[i],NULL,reader,&j);
   }
 for(j=0;j<n;j++)
   pthread_join(t1[j],NULL);
 return 1;

}

void *reader(void* arg) {

 int val=*(int*)arg;
 printf("%d Thinking\n",val+1);
 pthread_mutex_lock(&mut[val%n]);
 pthread_mutex_lock(&mut[(val+1)%n]);
 printf("%d Eating\n",val+1);
 sleep(3);
 pthread_mutex_unlock(&mut[val%n]);
 pthread_mutex_unlock(&mut[(val+1)%n]);
 printf("%d Finished Eating\n",val+1);

} </syntaxhighlight>