代码拉取完成,页面将自动刷新
#pragma once
#include <iostream>
#include <vector>
#include <pthread.h>
#include <mutex>
#include "sem.hpp"
const int DEFALT = 5;
template <class T>
class RingQueue
{
public:
RingQueue(int default_num = DEFALT)
:_ring_queue( DEFALT),
_num( DEFALT),
_c_step(0),
_p_step(0),
space_sem_( DEFALT),
data_sem_(0)
{
pthread_mutex_init(&clock, nullptr);
pthread_mutex_init(&plock, nullptr);
}
~RingQueue()
{
pthread_mutex_destroy(&clock);
pthread_mutex_destroy(&plock);
}
// 生产者的临界资源是下标
void push(const T &in)
{
space_sem_.p(); // 先申请信号量
pthread_mutex_lock(&plock);
_ring_queue[_p_step++] = in;
_p_step %= _num;
pthread_mutex_unlock(&plock);
data_sem_.v();
}
// 消费者的临界资源是下标
void pop(T *out)
{
data_sem_.p();
pthread_mutex_lock(&clock);
// 一定是竞争成功的消费者线程 -- 就一个!
*out = _ring_queue[_c_step++];
_c_step %= _num;
pthread_mutex_unlock(&clock);
space_sem_.v();
}
private:
std::vector<T> _ring_queue;
int _num;
int _c_step; // 消费下标
int _p_step; // 生产下标
Sem space_sem_;
Sem data_sem_;
pthread_mutex_t clock;
pthread_mutex_t plock;
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。