libcw/cwSpScQueueTmpl.h

89 lines
1.8 KiB
C
Raw Normal View History

2020-04-19 01:24:42 +00:00
#ifndef cwSpScQueueTmpl_H
#define cwSpScQueueTmpl_H
namespace cw
{
template< typename T >
class spScQueueTmpl
{
public:
spScQueueTmpl( unsigned eleN )
{
_aN = eleN;
_aV = mem::allocZ<T>(eleN);
_wi.store(0,std::memory_order_release);
_ri.store(0,std::memory_order_release);
2020-04-19 01:24:42 +00:00
}
virtual ~spScQueueTmpl()
{
mem::release(_aV);
}
T* get()
{
unsigned wi = _wi.load( std::memory_order_relaxed );
return _aV + wi;
2020-04-19 01:24:42 +00:00
}
rc_t publish()
2020-04-19 01:24:42 +00:00
{
unsigned ri = _ri.load( std::memory_order_acquire );
unsigned wi = _wi.load( std::memory_order_relaxed ); // _wi is written in this thread
2020-04-19 01:24:42 +00:00
// calc. the count of full elements
unsigned n = wi >= ri ? wi-ri : (_aN-ri) + wi;
// there must always be at least one empty element because
// wi can never be advanced to equal ri.
if( n >= _aN-1 )
return kBufTooSmallRC;
wi = (wi+1) % _aN;
// advance the write position
2020-04-19 01:24:42 +00:00
_wi.store( wi, std::memory_order_release );
return kOkRC;
}
T* pop()
{
unsigned ri = _ri.load( std::memory_order_relaxed );
unsigned wi = _wi.load( std::memory_order_acquire );
unsigned n = wi >= ri ? wi-ri : (_aN-ri) + wi;
if( n == 0 )
return nullptr;
T* v = _aV + ri;
2020-04-19 01:24:42 +00:00
ri = (ri+1) % _aN;
_ri.store( ri, std::memory_order_release);
return v;
}
private:
unsigned _aN = 0;
T* _aV = nullptr;
2020-04-19 01:24:42 +00:00
std::atomic<unsigned> _wi;
std::atomic<unsigned> _ri;
// Note: // _wi==_ri indicates an empty buffer.
// _wi may never be advanced such that it equals _ri, however
// _ri may be advanced such that it equals _wi.
};
rc_t testSpScQueueTmpl();
}
#endif