fork download
  1. #include<stdio.h>
  2. #include<semaphore.h>
  3. #include<fcntl.h>
  4. #include<sys/types.h>
  5. #include<sys/stat.h>
  6. #include<unistd.h>
  7. #include<pthread.h>
  8. struct{
  9. int data[5];
  10. sem_t *mutex[5];
  11. }sh;
  12. char *name[]={"p1","p2","p3","p4","p5"};
  13. void *work(void *);
  14. main()
  15. {
  16. pthread_t tid[5];
  17. int i;
  18. for(i=0;i<5;i++)
  19. {
  20. sh.mutex[i]=sem_open(name[i],O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,1);//
  21. }
  22. /* visit www.rgpv.tk for more */
  23. pthread_setconcurrency(6);
  24. setbuf(stdout,NULL);
  25. for(i=0;i<5;i++)
  26. pthread_create(&tid[i],NULL,work,&i);
  27. for(i=0;i<5;i++)
  28. pthread_join(tid[i],NULL);
  29. for(i=0;i<5;i++)
  30. sem_unlink(name[i]);
  31. }
  32. void *work(void *arg)
  33. {
  34. int p,i=1;
  35. p=*((int *)arg);
  36. while(i++<2)
  37. {
  38. sem_wait(sh.mutex[p]);
  39. sem_wait(sh.mutex[(p+1)%5]);
  40. /* aditya jain */
  41. sh.data[p]=1;
  42. printf("p%d[%d %d %d %d %d]\n",p+1,sh.data[0],sh.data[1],sh.data[2],sh.data[3],sh.data[4]);
  43. sleep(1);//eating
  44. sh.data[p]=0;
  45. sem_post(sh.mutex[p]);
  46. sem_post(sh.mutex[(p+1)%5]);
  47. sleep(2);//thinking
  48. }
  49. }
Success #stdin #stdout 0s 20600KB
stdin
Standard input is empty
stdout
p1[1 0 0 0 0]
p1[1 0 0 0 0]
p1[1 0 0 0 0]
p1[1 0 0 0 0]
p1[1 0 0 0 0]