jfcmacro

crearProcSemPosix.cpp

Mar 14th, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <semaphore.h>
  3. #include <unistd.h>
  4. #include <cstdlib>
  5. #include <cstring>
  6. #include <cerrno>
  7.  
  8. using namespace std;
  9.  
  10. void* cliente(void *);
  11. void* servidor(void *);
  12.  
  13. int
  14. main(int argc, char *argv[]) {
  15.  
  16.   sem_t *sem = new sem_t;
  17.  
  18.   if (sem_init(sem, 0, 0) == -1) {
  19.     cerr << "Error creando el semaforo: " <<
  20.       strerror(errno) << endl;
  21.     return EXIT_FAILURE;
  22.   }
  23.  
  24.   pthread_t hSrv;
  25.   pthread_t hCln;
  26.  
  27.   pthread_create(&hSrv, nullptr, servidor, (void *) sem);
  28.   pthread_create(&hCln, nullptr, cliente, (void *) sem);
  29.  
  30.   pthread_join(hSrv, nullptr);
  31.   pthread_join(hCln, nullptr);
  32.  
  33.   return EXIT_SUCCESS;
  34. }
  35.  
  36. void* cliente(void *arg) {
  37.  
  38.   sem_t *sem = (sem_t *) arg;
  39.   for (;;) {
  40.     sleep(10);
  41.     sem_post(sem);
  42.   }
  43. }
  44.  
  45. void* servidor(void *arg) {
  46.  
  47.   sem_t *sem = (sem_t *) arg;
  48.  
  49.   for (;;) {
  50.     cout << "Esperando para imprimir" << endl;
  51.     sem_wait(sem);
  52.     cout << "Impresion lista" << endl;
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment