0
点赞
收藏
分享

微信扫一扫

考研 操作系统:吸烟者问题

醉东枫 2022-01-24 阅读 24
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <iostream>

int num = 0;
sem_t psem[4];
void* Producer(void* args) {
  while (1) {
    if (num % 3 == 0) {
      sleep(1);
      std::cout << "Producer create tool0!" << std::endl;
      sem_post(&psem[0]);

    } else if (num % 3 == 1) {
      sleep(1);
      std::cout << "Producer create tool1!" << std::endl;
      sem_post(&psem[1]);

    } else if (num % 3 == 2) {
      sleep(1);
      std::cout << "Producer create tool2!" << std::endl;
      sem_post(&psem[2]);
    }
    num++;
    sem_wait(&psem[3]);
  }
}

void* Smoker1(void* args) {
  while (1) {
    sem_wait(&psem[0]);
    sleep(1);
    std::cout << "Smoker1 uses tool0!" << std::endl;
    sem_post(&psem[3]);
  }
}

void* Smoker2(void* args) {
  while (1) {
    sem_wait(&psem[1]);
    sleep(1);
    std::cout << "Smoker2 uses tool1!" << std::endl;
    sem_post(&psem[3]);
  }
}

void* Smoker3(void* args) {
  while (1) {
    sem_wait(&psem[2]);
    sleep(1);
    std::cout << "Smoker3 uses tool2!" << std::endl;
    sem_post(&psem[3]);
  }
}

int main() {
  sem_init(&psem[3], 0, 0);
  sem_init(&psem[0], 0, 0);
  sem_init(&psem[1], 0, 0);
  sem_init(&psem[2], 0, 0);
  pthread_t smoker[3], producer;
  pthread_create(&producer, NULL, Producer, NULL);
  pthread_create(&smoker[0], NULL, Smoker1, NULL);
  pthread_create(&smoker[1], NULL, Smoker2, NULL);
  pthread_create(&smoker[2], NULL, Smoker3, NULL);
  pthread_detach(producer);

  for (int i = 0; i < 3; i++) {
    pthread_detach(smoker[i]);
  }

  while (true) {
    sleep(1);
    std::cout << "wait...." << std::endl;
  }
  return 0;
}
举报

相关推荐

0 条评论