Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4.  
  5. sem_t canConsume;
  6. sem_t canProduce;
  7. sem_t mutex;
  8.  
  9. bool consumeFinish   = false;
  10. bool produceFinish   = false;
  11.  
  12. size_t bufferSize    = 0;
  13. unsigned int *buffer = nullptr;
  14.  
  15. namespace TextColor {
  16.     const std::string RED_COLOR     = "\033[1;31m";
  17.     const std::string GREEN_COLOR   = "\033[1;32m";
  18.     const std::string YELLOW_COLOR  = "\033[1;33m";
  19.     const std::string DEF_COLOR     = "\033[0m";
  20. }
  21.  
  22. void printBuffer() {
  23.     std::cout << TextColor::YELLOW_COLOR << "Buffer: ";
  24.     for (size_t i = 0; i < bufferSize; i++) {
  25.         if (buffer[i] == 0) {
  26.             std::cout << TextColor::RED_COLOR;
  27.         } else {
  28.             std::cout << TextColor::GREEN_COLOR;
  29.         }
  30.         std::cout << buffer[i] << " ";
  31.     }
  32.     std::cout << TextColor::DEF_COLOR << std::endl;
  33. }
  34.  
  35.  
  36. unsigned int push_buffer(bool consume) {
  37.     for (int i = 0; i < bufferSize; i++) {
  38.         if (consume) {
  39.             if (buffer[i] == 1) {
  40.                 buffer[i] = 0;
  41.                 return i;
  42.             }
  43.         } else {
  44.             if (buffer[i] == 0) {
  45.                 buffer[i] = 1;
  46.                 return i;
  47.             }
  48.         }
  49.     }
  50. }
  51.  
  52. void *produce(void *threadId) {
  53.     int id = *((int *) threadId);
  54.    
  55.     do {
  56.         sem_wait(&canProduce);
  57.         sem_wait(&mutex);
  58.        
  59.         // produce action
  60.         push_buffer(false);
  61.        
  62.  
  63.         sem_post(&mutex);
  64.         sem_post(&canConsume);
  65.     } while (!produceFinish);
  66.  
  67.     pthread_exit(0);
  68. }
  69.  
  70. void *consume(void *threadId) {
  71.     int id = *((int *) threadId);
  72.  
  73.     do {
  74.         sem_wait(&canConsume);
  75.         sem_wait(&mutex);
  76.        
  77.         // consume action
  78.         push_buffer(true);
  79.  
  80.         sem_post(&mutex);
  81.         sem_post(&canProduce);
  82.     } while (!consumeFinish);
  83.    
  84.     pthread_exit(0);
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement