Advertisement
Guest User

Thread

a guest
Oct 22nd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5.  
  6. int fd[2];//File descriptor for creating a pipe
  7.  
  8. //This function continously reads fd[0] for any input data byte
  9. //If available, prints
  10.  
  11. void *reader()
  12. {
  13.  
  14. int count = 0;
  15. sleep (25);
  16. //Delay in starting the reading from the pipe
  17.  
  18. while(1){
  19. char ch;
  20. int result;
  21.  
  22. result = read (fd[0],&ch,1);
  23. if (result != 1) {
  24. perror("read");
  25. exit(3);
  26. } printf ("Reader: %d %c\n",++count,ch);
  27. }
  28. }
  29.  
  30. //This function continously writes Alphabet into fd[1]
  31.  
  32. void *writer()
  33. {
  34. int result;
  35. char ch='A'; int count = 0;
  36.  
  37. while(1){
  38.  
  39. result = write (fd[1], &ch,1);
  40. if (result != 1){
  41. perror ("write");
  42. exit (2);
  43. }
  44.  
  45. printf ("Writer: %d %c\n", ++count, ch);
  46.  
  47. if(ch == 'Z')
  48. ch = 'A'-1;
  49.  
  50. ch++;
  51. }
  52. }
  53.  
  54. int main()
  55. {
  56. pthread_t tid1,tid2;
  57. int result;
  58.  
  59. result = pipe (fd);
  60.  
  61. if (result < 0){
  62. perror("pipe ");
  63. exit(1);
  64. }
  65.  
  66. pthread_create(&tid1,NULL,reader,NULL);
  67. pthread_create(&tid2,NULL,writer,NULL);
  68.  
  69. pthread_join(tid1,NULL);
  70. pthread_join(tid2,NULL);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement