Pergunta

This was from compsci lecture quiz that my professor want us to challenge. he said that this class is about circular buffer but has got major problem. I've try to think for whole day but have no clue. please give me some ideas

#include <stdint.h>
#include <boost/thread.hpp>

template <typename T, uint32_t max>
class CircularBuffer
{
public:

    CircularBuffer() : m_WriteOffset(0), m_ReadOffset(0){}
    ~CircularBuffer(){};

    void push( T val )
    {
        boost::lock_guard<boost::mutex> guard( m_Mutex );
        m_Buffer[m_WriteOffset++] = val;
    }

    T pull()
    {
        boost::lock_guard<boost::mutex> guard( m_Mutex );
        return m_Buffer[m_ReadOffset++];
    }

private:

    boost::mutex m_Mutex;

    enum { MAX_SIZE = max };
    T m_Buffer[MAX_SIZE];
    uint32_t m_WriteOffset;
    uint32_t m_ReadOffset;
};
Foi útil?

Solução

full, empty methods not implemented. Offset increment must be like m_ReadOffset = (m_ReadOffset + 1) % MAX_SIZE, then only the buffer will be circular. Both read and write offset I mean.

Outras dicas

You asked for a hint, so here is one:

What happens if you push MAX_SIZE+1 elements before reading any?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top