SHARE
TWEET

Untitled

a guest Apr 23rd, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4. int x = 1, y = 2, z = 3;
  5. sem_t semXY;
  6. sem_t semZ;
  7. void* a(void* param){
  8.   int i = 0;
  9.   while(1){
  10.     x = x + x;
  11.     y = y + y;
  12.     sem_post(&semXY);
  13.     sem_wait(&semZ);
  14.     printf("%d - %d = %d\n", y, x, z);
  15.     if(++i == 1) break;
  16.   }
  17.   return 0;
  18. }
  19. void* b(void* param){
  20.   int i = 0;
  21.   while(1){
  22.     sem_wait(&semXY);
  23.     z = y - x;
  24.     sem_post(&semZ);
  25.     if(++i == 1) break;
  26.   }
  27.   return 0;
  28. }
  29. int main(){
  30.    pthread_t nitA, nitB;
  31.    
  32.    sem_init(&semXY, 0, -1);
  33.    sem_init(&semZ, 0, 0);
  34.    
  35.    pthread_create(&nitA, 0, a, 0);
  36.    pthread_create(&nitB, 0, b, 0);
  37.    
  38.    pthread_join(nitA, 0);
  39.    pthread_join(nitA, 0);
  40.  
  41.    sem_destroy(&semXY);
  42.    sem_destroy(&semZ);
  43.    
  44.    return 0;
  45. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top