gpt4 book ai didi

c++ - 这是在 C++ 中实现有界缓冲区的正确方法吗

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:30:16 29 4
gpt4 key购买 nike

<分区>

我正在开发一个处理多个线程访问、存入和退出有界缓冲区容器的程序。我注意到线程存在一些主要问题,并怀疑我的缓冲区在某处部分或根本不正确。

为了确保我知道我在用它做什么,我希望能检查一下我的缓冲区代码。该类使用我在其他地方实现的信号量,我假设它现在可以工作(如果不能,我会尽快弄清楚!)我添加了试图解释我的推理的评论。

首先是.h文件:

#ifndef BOUNDED_BUFFER_H
#define BOUNDED_BUFFER_H

#include "Semaphore.H"
#include <string>
#include <vector>

using namespace std;

class Item{ //supposed to eventually be more extensible...seems silly with just a string for now

public:
Item(string _content){content = _content;}
string GetContent() {return content;}

private:
};

class BoundedBuffer{

public:
BoundedBuffer();

void Deposit(Item* _item);
Item* Retrieve();
int GetNumItems() {return count;}
vector<Item*> GetBuffer() {return buffer;}
void SetSize(int _size){
capacity = _size;
buffer.reserve(_size); //or do I need to call "resize"
}

private:
int capacity;
vector<Item*> buffer; //I originally wanted to use an array but had trouble with
//initilization/sizing, etc.
int nextin;
int nextout;
int count;

Semaphore notfull; //wait on this one before depositing an item
Semaphore notempty; //wait on this one before retrieving an item
};

#endif

接下来,.cpp:

#include "BoundedBuffer.H"
#include <iostream>

using namespace std;

BoundedBuffer::BoundedBuffer(){

notfull.SetValue(0);
notempty.SetValue(0);
nextin = 0;
nextout = 0;
count = 0;
}

void BoundedBuffer::Deposit(Item* _item){
if(count == capacity){
notfull.P(); //Cannot deposit into full buffer; wait
}

buffer[nextin] = _item;
nextin = (nextin + 1) % capacity; //wrap-around
count += 1;
notempty.V(); //Signal that retrieval is safe
}

Item* BoundedBuffer::Retrieve(){
if(count == 0){
notempty.P(); //cannot take from empty buffer; wait
}

Item* x = buffer[nextout];
nextout = (nextout + 1) % capacity;
buffer.pop_back(); //or a different erase methodology?
count -= 1;
notfull.V(); //Signal that deposit is safe
return x;
}

我认为问题可能源于我选择 vector 作为底层容器(或者更确切地说,不正确地使用它),或者可能需要更多的安全阻塞机制(互斥锁等?)来自事情的样子,任何人都可以提供一些反馈吗?

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com