@ -14,10 +14,10 @@
# include "common/common_types.h"
# include "common/common_types.h"
namespace Common {
namespace Common {
template < typename T , bool NeedSize = true >
template < typename T >
class SPSCQueue {
class SPSCQueue {
public :
public :
SPSCQueue ( ) : size ( 0 ) {
SPSCQueue ( ) {
write_ptr = read_ptr = new ElementPtr ( ) ;
write_ptr = read_ptr = new ElementPtr ( ) ;
}
}
~ SPSCQueue ( ) {
~ SPSCQueue ( ) {
@ -26,12 +26,11 @@ public:
}
}
u32 Size ( ) const {
u32 Size ( ) const {
static_assert ( NeedSize , " using Size() on FifoQueue without NeedSize " ) ;
return size . load ( ) ;
return size . load ( ) ;
}
}
bool Empty ( ) const {
bool Empty ( ) const {
return ! read_ptr - > next . load ( ) ;
return Size ( ) = = 0 ;
}
}
T & Front ( ) const {
T & Front ( ) const {
@ -47,13 +46,13 @@ public:
ElementPtr * new_ptr = new ElementPtr ( ) ;
ElementPtr * new_ptr = new ElementPtr ( ) ;
write_ptr - > next . store ( new_ptr , std : : memory_order_release ) ;
write_ptr - > next . store ( new_ptr , std : : memory_order_release ) ;
write_ptr = new_ptr ;
write_ptr = new_ptr ;
if ( NeedSize )
size + + ;
+ + size ;
}
}
void Pop ( ) {
void Pop ( ) {
if ( NeedSize )
- - size ;
size - - ;
ElementPtr * tmpptr = read_ptr ;
ElementPtr * tmpptr = read_ptr ;
// advance the read pointer
// advance the read pointer
read_ptr = tmpptr - > next . load ( ) ;
read_ptr = tmpptr - > next . load ( ) ;
@ -66,8 +65,7 @@ public:
if ( Empty ( ) )
if ( Empty ( ) )
return false ;
return false ;
if ( NeedSize )
- - size ;
size - - ;
ElementPtr * tmpptr = read_ptr ;
ElementPtr * tmpptr = read_ptr ;
read_ptr = tmpptr - > next . load ( std : : memory_order_acquire ) ;
read_ptr = tmpptr - > next . load ( std : : memory_order_acquire ) ;
@ -103,13 +101,13 @@ private:
ElementPtr * write_ptr ;
ElementPtr * write_ptr ;
ElementPtr * read_ptr ;
ElementPtr * read_ptr ;
std : : atomic < u32 > size ;
std : : atomic < u32 > size {0 } ;
} ;
} ;
// a simple thread-safe,
// a simple thread-safe,
// single reader, multiple writer queue
// single reader, multiple writer queue
template < typename T , bool NeedSize = true >
template < typename T >
class MPSCQueue {
class MPSCQueue {
public :
public :
u32 Size ( ) const {
u32 Size ( ) const {
@ -144,7 +142,7 @@ public:
}
}
private :
private :
SPSCQueue < T , NeedSize > spsc_queue ;
SPSCQueue < T > spsc_queue ;
std : : mutex write_lock ;
std : : mutex write_lock ;
} ;
} ;
} // namespace Common
} // namespace Common