【问题标题】:About Ring buffer关于环形缓冲区
【发布时间】:2019-08-31 14:10:02
【问题描述】:

我必须创建一个具有并行进程的系统,该系统将使用环形缓冲区。“爸爸”进程当然必须创建信号量和分段并启动他们的儿子,然后他可以撤退并等待其他人完成。你会创建一个从键盘读取字符并将它们写入环形缓冲区的进程,创建一个生成文本并放入环形缓冲区的进程,然后创建一个从环形缓冲区读取并在屏幕上写入的进程。所有必要的资源都必须同步(当然)。

到目前为止,我已尝试过,但程序无法正常工作。有没有哪位专家可以帮助我解决这个问题。

这是.h文件:

 template<typename T>
class RingBuffer
{
private:
    T* _value;
    int size;  
    int front;
    int back;
    bool empty;

public:
    RingBuffer(int s);
    ~RingBuffer();
    void _add(T element);
    T get();
    void _write(RingBuffer *_value);
    void _read(RingBuffer *_value);
    bool is_empty();
    int get_size();
};

Here is .cpp file:

#include "RingBuffer.h"
#include <iostream>


template<typename T>
RingBuffer<T>::RingBuffer(int s)
    :size(s)
{
    _value = new T[size];
}

template<typename T>
RingBuffer<T>::~RingBuffer()
{
    if (_value!= nullptr)
    {
        delete[] _value;
    }
}

template<typename T>
void RingBuffer<T>::_add(T element)
{
    if (back == front & !empty)
    {
        return;
    }
    _value[back] = element;
    _value[back] = (back + 1) % size;
    empty = false;
}

template<typename T>
T RingBuffer<T>::get()
{
    if (back == front && empty)     

    {
        return 0;
    }
    int return_value = _value[front];
    front = (front + 1) % size;

    if (front == back)
        empty = true;
    return true;
}

template<typename T>
void RingBuffer<T>::_read(RingBuffer *_value)
{
    while (true)
    {
        std::cout << _value->get();
    }
}

template<typename T>
void RingBuffer<T>::_write(RingBuffer* _value)
{
    while (true)
    {
        std::string s;
        std::getline(std::cin,  s);
        for (int i = 0; i < s.size(); i++)
        {
            _value->_add(s[i]);
        }
        std::cout << std::endl;
    }
}


template<typename T>
int RingBuffer<T>::get_size()
{
    return size;
}

template<typename T>
bool RingBuffer<T>::is_empty()
{
    if (back == 0)
        return true;
    else
        return false;
}

Here is main function:
#include <iostream>
#include <thread>
#include <string>

#include "RingBuffer.h"

int main(){
int write = 0;
int read = 0;
    RingBuffer<std::string> _value(10);
    std::thread key(write, &_value);
    std::thread reader(read, &_value);
    key.join();
    reader.join();

    system("pause");
    return 0;
}

这两个是get()函数的错误。

// C2672 'std::invoke': 找不到匹配的重载函数

// 错误 C2893 无法专门化函数模板 'unknown-type std::invoke(_Callable &&,_Types &&...) //noexcept()'

【问题讨论】:

  • “不工作。” 不是简明的错误描述。 Edit你的问题。
  • 嗨!我在 Ringbuffer.cpp 文件中的 get 函数中有错误。我现在也发布了错误所说的内容..
  • 为什么要将指向环形缓冲区的指针传递给环形缓冲区的readwrite 方法?我希望 readwrite 方法在内部(成员)数据结构上运行,而不是在其他一些结构上运行(顺便说一下,指针可以指向任何地方,包括无效位置)。
  • Thomas Mathews 如果您为此写下代码,那绝对有很大帮助...

标签: c++ buffer ring


【解决方案1】:

您的模板定义不能在 .cpp 文件中。

查看here(更适合您的问题)或here了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多