/*
* RingBuf.h
*
* Created on: Feb 7, 2015 6:06:10 PM
* Author: xuzewen
*/
#ifndef RINGBUF_H_
#define RINGBUF_H_
#include <libmisc.h>
/**
*
* 多/单线程生产, 只能单线程消费, 尺寸固定为0x10000.
*
* */
class RingBuf
{
public:
ushort ccur; /** 消费游标. */
uint pcur; /** 生产游标. */
size_t* ring;
public:
RingBuf();
virtual ~RingBuf();
public:
bool push(void* e); /** 添加, 反复尝试, 直到成功为止. */
void* pop(); /** 弾出, 总是立即返回, 无元素时返回空. */
int size(); /** 返回元素个数. */
};
#endif /* RINGBUF_H_ */
实现:
/*
* RingBuf.cpp
*
* Created on: Feb 7, 2015 6:06:10 PM
* Author: xuzewen
*/
#include "RingBuf.h"
RingBuf::RingBuf()
{
this->pcur = 0;
this->ccur = 0;
this->ring = (size_t*) calloc(1, sizeof(size_t) * 0x10000);
}
/** 添加, 反复尝试, 直到成功为止. */
bool RingBuf::push(void* f)
{
while (!__sync_bool_compare_and_swap(this->ring + (this->pcur & 0x0000FFFF), 0, (size_t) f))