Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <semaphore.h>
- #include <pthread.h>
- sem_t canConsume;
- sem_t canProduce;
- sem_t mutex;
- bool consumeFinish = false;
- bool produceFinish = false;
- size_t bufferSize = 0;
- unsigned int *buffer = nullptr;
- namespace TextColor {
- const std::string RED_COLOR = "\033[1;31m";
- const std::string GREEN_COLOR = "\033[1;32m";
- const std::string YELLOW_COLOR = "\033[1;33m";
- const std::string DEF_COLOR = "\033[0m";
- }
- void printBuffer() {
- std::cout << TextColor::YELLOW_COLOR << "Buffer: ";
- for (size_t i = 0; i < bufferSize; i++) {
- if (buffer[i] == 0) {
- std::cout << TextColor::RED_COLOR;
- } else {
- std::cout << TextColor::GREEN_COLOR;
- }
- std::cout << buffer[i] << " ";
- }
- std::cout << TextColor::DEF_COLOR << std::endl;
- }
- unsigned int push_buffer(bool consume) {
- for (int i = 0; i < bufferSize; i++) {
- if (consume) {
- if (buffer[i] == 1) {
- buffer[i] = 0;
- return i;
- }
- } else {
- if (buffer[i] == 0) {
- buffer[i] = 1;
- return i;
- }
- }
- }
- }
- void *produce(void *threadId) {
- int id = *((int *) threadId);
- do {
- sem_wait(&canProduce);
- sem_wait(&mutex);
- // produce action
- push_buffer(false);
- sem_post(&mutex);
- sem_post(&canConsume);
- } while (!produceFinish);
- pthread_exit(0);
- }
- void *consume(void *threadId) {
- int id = *((int *) threadId);
- do {
- sem_wait(&canConsume);
- sem_wait(&mutex);
- // consume action
- push_buffer(true);
- sem_post(&mutex);
- sem_post(&canProduce);
- } while (!consumeFinish);
- pthread_exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement