用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

C++无锁循环缓冲队列

2012-10-08 作者: 神马举报

[c++]代码库

#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif

#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif

// 无锁缓冲队列.
class circular_buffer
{
public:
	circular_buffer ( int buf_size )
			: m_buffer_size ( buf_size )
			, m_circle_buffer ( NULL )
			, m_write_p ( 0 )
			, m_read_p ( 0 )
	{
		m_circle_buffer = new char[m_buffer_size];
	}

	~circular_buffer()
	{
		if ( m_circle_buffer )
			delete[] m_circle_buffer;
		m_circle_buffer = NULL;
	}

	void clear()
	{
		m_write_p = 0;
		m_read_p = 0;
	}

	unsigned int size()
	{
		return m_buffer_size - ( m_write_p - m_read_p );
	}

	unsigned int used()
	{
		return m_write_p - m_read_p;
	}

	unsigned int put_data ( char* buffer, unsigned int len )
	{
		unsigned int l;
		len = _min ( len, m_buffer_size - m_write_p + m_read_p );
		/* first put the data starting from fifo->in to buffer end */
		l = _min ( len, m_buffer_size - ( m_write_p & ( m_buffer_size - 1 ) ) );
		memcpy ( m_circle_buffer + ( m_write_p & ( m_buffer_size - 1 ) ), buffer, l );
		/* then put the rest (if any) at the beginning of the buffer */
		memcpy ( m_circle_buffer, buffer + l, len - l );
		m_write_p += len;
		return len;
	}

	unsigned int get_data ( char* buffer, unsigned int len )
	{
		unsigned int l;
		len = _min ( len, m_write_p - m_read_p );
		/* first get the data from fifo->out until the end of the buffer */
		l = _min ( len, m_buffer_size - ( m_read_p & ( m_buffer_size - 1 ) ) );
		memcpy ( buffer, m_circle_buffer + ( m_read_p & ( m_buffer_size - 1 ) ), l );
		/* then get the rest (if any) from the beginning of the buffer */
		memcpy ( buffer + l, m_circle_buffer, len - l );
		m_read_p += len;
		return len;
	}

protected:
	inline unsigned int _max ( unsigned int a, unsigned int b )
	{
		return max ( a, b );
	}

	inline unsigned int _min ( unsigned int a, unsigned int b )
	{
		return min ( a, b );
	}

private:
	int m_buffer_size;
	char* m_circle_buffer;
	unsigned int m_write_p;
	unsigned int m_read_p;
};


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...