Line 13: Line 13:
 
{
 
{
 
   pthread_t t1[5];
 
   pthread_t t1[5];
   int i,j=0,k;
+
   int i,j = 0,k;
 
   n = 5;
 
   n = 5;
   for(i=0;i<n;i++)
+
   for(i = 0; i < n; i++)
 
     {
 
     {
 
       j=i;
 
       j=i;
       pthread_create(&t1[i],NULL,reader,&j);
+
       pthread_create(&t1[i], NULL, reader, &j);
 
     }
 
     }
   for(j=0;j<n;j++)
+
   for(j = 0; j < n; j++)
     pthread_join(t1[j],NULL);
+
     pthread_join(t1[j], NULL);
 
   return 1;
 
   return 1;
 
}
 
}
Line 27: Line 27:
 
void *reader(void* arg)
 
void *reader(void* arg)
 
{
 
{
   int val=*(int*)arg;
+
   int val = *(int*)arg;
   printf("%d Thinking\n",val+1);
+
   printf("%d Thinking\n", val + 1);
   pthread_mutex_lock(&mut[val%n]);
+
   pthread_mutex_lock(&mut[val % n]);
   pthread_mutex_lock(&mut[(val+1)%n]);
+
   pthread_mutex_lock(&mut[(val + 1) % n]);
   printf("%d Eating\n",val+1);
+
   printf("%d Eating\n", val + 1);
 
   sleep(3);
 
   sleep(3);
   pthread_mutex_unlock(&mut[val%n]);
+
   pthread_mutex_unlock(&mut[val % n]);
   pthread_mutex_unlock(&mut[(val+1)%n]);
+
   pthread_mutex_unlock(&mut[(val + 1) % n]);
   printf("%d Finished Eating\n",val+1);
+
   printf("%d Finished Eating\n",val + 1);
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 22:00, 13 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>