Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3.                             Online C Compiler.
  4.                 Code, Compile, Run and Debug C program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <semaphore.h>
  12. #include <pthread.h>
  13. #include <wait.h>
  14. #include <unistd.h>
  15.  
  16. sem_t pingsemafor,pongsemfor;
  17.  
  18. void *ping(void *arg){
  19.     while(1){
  20.        
  21.         sem_wait(&pingsemafor);
  22.         printf("\n Ping");
  23.         sleep(1);
  24.        
  25.         sem_post(&pongsemfor);
  26.     }
  27.    
  28. }
  29.  
  30. void *pong(void *arg){
  31.     while(1){
  32.        
  33.         sem_wait(&pongsemfor);
  34.         printf("\n Pong");
  35.         sleep(1);
  36.        
  37.         sem_post(&pingsemafor);
  38.     }
  39.    
  40. }
  41.  
  42.  
  43.  
  44.  
  45. int main()
  46. {
  47.     sem_init(&pingsemafor,0,1);
  48.     sem_init(&pongsemfor,0,0);
  49.    
  50.     pthread_t ping_thread,pong_thread;
  51.    
  52.    
  53.     pthread_create(&ping_thread,NULL,ping,NULL);
  54.      pthread_create(&pong_thread,NULL,ping,NULL);
  55.      
  56.      pthread_join(&ping_thread,NULL);
  57.      pthread_join(&pong_thread,NULL);
  58.    
  59.    
  60.  
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement