daily pastebin goal
34%
SHARE
TWEET

Untitled

a guest Mar 21st, 2019 45 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. /*
  3.  *  semex.c
  4.  *
  5.  *  This module demonstrates POSIX semaphores.
  6.  *
  7.  *  Operation:
  8.  *      A counting semaphore is created, primed with 0 counts.
  9.  *      Five consumer threads are started, each trying to obtain
  10.  *      the semaphore.
  11.  *      A producer thread is created, which periodically posts
  12.  *      the semaphore, unblocking one of the consumer threads.
  13.  *
  14. */
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <sys/neutrino.h>
  19. #include <pthread.h>
  20. #include <semaphore.h>
  21. #include <fcntl.h>
  22. #include <sys/stat.h>
  23. #include <malloc.h>
  24.  
  25. /*
  26.  *  our global variables, and forward references
  27. */
  28.  
  29. sem_t   *mySemaphore;
  30.  
  31. void    *producer (void *);
  32. void    *consumer (void *);
  33.  
  34. char    *progname = "semex";
  35.  
  36. #define SEM_NAME "/Semex"
  37.  
  38. int main ()
  39. {
  40.     int     i;
  41.  
  42.     setvbuf (stdout, NULL, _IOLBF, 0);
  43.  
  44. #define  Named
  45. #ifdef  Named
  46.     printf ("%s:  named semaphore\n", progname);
  47.  
  48.     mySemaphore = sem_open (SEM_NAME, O_CREAT|O_EXCL, S_IRWXU, 0);
  49.     /* not sharing with other process, so immediately unlink */
  50.     //sem_unlink( SEM_NAME );
  51. #else   // Named
  52.     printf ("%s:  unnamed semaphore\n", progname);
  53.     mySemaphore = malloc (sizeof (sem_t));
  54.     sem_init (mySemaphore, 1, 0);
  55. #endif  // Named
  56.  
  57.     for (i = 0; i < 5; i++) {
  58.         pthread_create (NULL, NULL, consumer, (void *) i);
  59.     }
  60.  
  61.     pthread_create (NULL, NULL, producer, (void *) 1);
  62.  
  63.     sleep (120);     // let the threads run
  64.     printf ("%s:  main, exiting\n", progname);
  65.  
  66.     return (EXIT_SUCCESS);
  67. }
  68.  
  69. /*
  70.  *  producer
  71. */
  72.  
  73. void *
  74. producer (void *i)
  75. {
  76.     while (1) {
  77.         sleep (1);
  78.         printf ("%s:  (producer %d), posted semaphore\n", progname, (int) i);
  79.         sem_post (mySemaphore);
  80.     }
  81.     return (NULL);
  82. }
  83.  
  84. /*
  85.  *  consumer
  86. */
  87.  
  88. void *
  89. consumer (void *i)
  90. {
  91.     while (1) {
  92.         sem_wait (mySemaphore);
  93.         printf ("%s:  (consumer %d) got semaphore\n", progname, (int) i);
  94.     }
  95.     return (NULL);
  96. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top