我的程序应该在c ++中实现线程安全堆栈 当我想启动程序时出现错误:
调试断言失败! ...... \ vector line 1201
表达式:向量下标超出范围
我绝对不知道代码有什么问题
#include <condition_variable>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#define NUM_ELEMENTS 10
using namespace std;
class Stack
{
protected:
vector<int> stack;
int topOfStack;
int maxSize;
mutable mutex _mutex;
mutable condition_variable cv;
public:
Stack(int size);
int top() const;
int pop();
void push(int element);
bool isFull() const;
bool isEmpty() const;
};
Stack::Stack(int size)
{
stack.reserve(size);
maxSize = size;
topOfStack = 0;
}
int Stack::top() const
{
unique_lock<mutex> lck(_mutex);
// sperren, solange kein Wert da ist
while (isEmpty())
cv.wait(lck);
int val = stack[topOfStack - 1];
return val;
}
int Stack::pop()
{
// Kritischer Bereich - sperren
unique_lock<mutex> lck(_mutex);
// sperren, solange kein Wert am Stack ist
while (isEmpty())
cv.wait(lck);
// Wert zwischenspeichern und Stack-Pointer -1
// danach werden wartende Threads benachrichtigt
topOfStack--;
int val = stack[topOfStack];
cv.notify_all();
return val;
}
void Stack::push(int element)
{
// Kritischer Bereich - sperren
unique_lock<mutex> lck(_mutex);
// sperren, solange der Stack voll ist
while (isFull())
cv.wait(lck);
// Wert speichern und Stack-Pointer +1
// danach werden wartende Threads benachrichtigt
stack[topOfStack] = element;
topOfStack++;
cv.notify_all();
}
bool Stack::isEmpty() const
{
return topOfStack == 0;
}
bool Stack::isFull() const
{
return topOfStack == maxSize;
}
// PRODUCER
class Producer
{
protected:
shared_ptr<Stack> stack;
public:
Producer(shared_ptr<Stack> stack);
void produce(size_t amount);
};
//CONSUMER
class Consumer
{
protected:
shared_ptr<Stack> stack;
public:
Consumer(shared_ptr<Stack> stack);
void consume(size_t amount);
};
Producer::Producer(shared_ptr<Stack> stack)
: stack(stack)
{}
void Producer::produce(size_t amount)
{
for (size_t i = 0; i < amount; i++)
{
cout << "Produce: " << i << endl;
stack->push(i);
}
}
Consumer::Consumer(shared_ptr<Stack> stack)
: stack(stack)
{}
void Consumer::consume(size_t amount)
{
for (size_t i = 0; i < amount; i++)
{
cout << "Consume: " << stack->pop() << endl;
}
}
// ////////////////////////////////////////////////////////////////////////////
int main()
{
shared_ptr<Stack> stack(new Stack(3));
Producer producer(stack);
Consumer consumer(stack);
thread consumerThread(&Consumer::consume, &consumer, NUM_ELEMENTS);
thread producerThread(&Producer::produce, &producer, NUM_ELEMENTS);
consumerThread.join();
producerThread.join();
return 0;
}
答案 0 :(得分:0)
您的vector<int> stack
成员的尺寸为0
,并且永远保持该尺寸0
。我没有看到任何在代码中更改其大小的尝试。难怪任何对stack
的索引访问都会产生未定义的行为,包括这个&#34;超出范围&#34;错误。
提示:如果要更改std::vector
的大小,则相应的方法称为resize
,而不是reserve
。后者更改容量,而不是矢量的 size 。