Esta é uma maneira correta de implementar um buffer limitado em C ++ [closed]
Eu estou trabalhando em um programa que lida com vários threads acessando, depositando e retirando de um contêiner de buffer limitado. Eu notei alguns problemas maiores com os threads e suspeito que meu buffer está parcial ou fundamentalmente incorreto em algum lugar.
Para ter certeza de que sei o que estou fazendo com isso, gostaria que meu código de buffer fosse analisado. A classe usa um Semaphore que eu implementei em outro lugar, o qual eu assumirei que funciona por enquanto (se não, eu vou descobrir isso em breve!) Eu adicionei comentários que tentam explicar o meu raciocínio.
Primeiro, o arquivo .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
Em seguida, o .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;
}
Eu acho que os problemas poderiam surgir da minha escolha de um vetor como o recipiente subjacente (ou, melhor, um uso incorreto dele), ou talvez a necessidade de mais mecanismos de bloqueio para segurança (mutex locks, etc.?). coisas, alguém pode oferecer algum feedback?