Advertisement
CrozzCyborg

thread2.cpp

Mar 16th, 2014
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. /*
  2.  * thread2.cpp
  3.  * Copyright (C) 2014 Crozz Cyborg <crozz@segv.sx>
  4.  *
  5.  * Distributed under terms of the GPLv3 license.
  6.  */
  7.  
  8. #include <unistd.h>
  9. #include <cstdio>
  10. #include <pthread.h>
  11.  
  12. #include <semaphore.h>
  13.  
  14. sem_t semaforo; // Declaramos el semaforo
  15.  
  16. void *thr1(void *null){
  17.     printf("[1] Terminando trabajo en\n");
  18.  
  19.     for(int i=3;i >= 1;i--){
  20.         printf("%d...\n", i);
  21.         sleep(2);
  22.     }
  23.  
  24.     printf("[1] Trabajo terminado\n");
  25.  
  26.     sem_post(&semaforo); // Cambiamos el valor del semaforo
  27.  
  28.     pthread_exit(NULL);
  29. }
  30.  
  31. void *thr2(void *null){
  32.     printf("[2] Esperando que el thread1 termine su trabajo\n");
  33.  
  34.     sem_wait(&semaforo); // Hacemos el wait del semaforo
  35.  
  36.     printf("[2] thread1 ha terminado su trabajo\n");
  37.     pthread_exit(NULL);
  38. }
  39.  
  40. int main(){
  41.     sem_init(&semaforo, 1, 0); // Iniciamos el semaforo en 0
  42.  
  43.     pthread_t thread1;
  44.     pthread_t thread2;
  45.  
  46.     pthread_create(&thread1, NULL, thr1, NULL);
  47.     pthread_create(&thread2, NULL, thr2, NULL);
  48.  
  49.     pthread_exit(NULL);
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement