// 采用信号量与缓冲队列实现生产者与消费者模式
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "pthread.h"
#include <string.h>
#include <semaphore.h>
#include <mutex>
#include <queue>
#include <thread>
#include <iostream>
class SEM_MODEL
{
private:
bool runnnig_;
std::thread pro_thread_; // 生产者进程
std::thread cons_thread_; // 消费者进程
std::mutex mutex_;
sem_t semP; // 生产者信号量
sem_t semC; // 消费者信号
std::queue<int> buffer; // 缓冲队列
public:
SEM_MODEL();
SEM_MODEL(int num1, int num2);
~SEM_MODEL();
public:
void start();
void stop();
static SEM_MODEL &instance()
{
static SEM_MODEL s;
return s;
}
private:
void product(); // 进行生产
void consume(); // 进行消费
};
SEM_MODEL::SEM_MODEL()
{
runnnig_ = false;
sem_init(&semP, 0, 5);
sem_init(&semC, 0, 0);
}
SEM_MODEL::SEM_MODEL(int num1, int num2)
{
runnnig_ = false;
sem_init(&semP, 0, num1);
sem_init(&semC, 0, num2);
}
SEM_MODEL::~SEM_MODEL()
{
runnnig_ = false;
}
void SEM_MODEL::start()
{
runnnig_ = true;
pro_thread_ = std::thread(&SEM_MODEL::product, this);
cons_thread_ = std::thread(&SEM_MODEL::consume, this);
}
void SEM_MODEL::stop()
{
runnnig_ = false;
if (pro_thread_.joinable())
{
pro_thread_.join();
}
if (cons_thread_.joinable())
{
cons_thread_.join();
}
}
void SEM_MODEL::product()
{
while (runnnig_)
{
sem_wait(&semP);
mutex_.lock();
int elem = (rand() + 100) % 101;
this->buffer.push(elem);
std::cout << "正在写入元素:" << elem << std::endl;
mutex_.unlock();
sem_post(&semC);
usleep(20);
}
}
void SEM_MODEL::consume()
{
while (runnnig_)
{
sem_wait(&semC);
mutex_.lock();
int elem = buffer.front();
buffer.pop();
std::cout << "正在弹出元素:" << elem << std::endl;
mutex_.unlock();
sem_post(&semP);
usleep(10);
}
}
int main()
{
SEM_MODEL sem_model(5, 0);
sem_model.start();
// 开始启动
while (true)
{
}
sem_model.stop();
return 0;
}