# Lockless Queue Multiple-Reader Singler-Writer in C++

I wrote a lockless queue for sending small objects from a single thread to a random worker thread.

Assumptions:

• x86/x86_64 compiled with GCC
• notifying a thread that data is available is done elsewhere
• T is copy assignable and sizeof(T) is small
• N is a power of two

Any suggestions welcome.

//RnW1FifoFixed.h
#pragma once
#include <memory>

//multiple reader single writer first in first out fixed length ring buffer queue
//compatible with x86/x86_64 GCC
template<typename T,uint32_t N> class RnW1FifoFixed
{
private:
public:
RnW1FifoFixed()
{
static_assert(std::is_default_constructible<T>::value,"T does not have a default constructor.");
static_assert(std::is_copy_assignable<T>::value,"T does not support copy assignment.");
static_assert(N!=0,"N is too small.");
static_assert(N!=0x80000000,"N is too large.");
static_assert((N&(N-1))==0,"N is not a power of two.");
}
bool Write(T t)
{
//full
return false;
//CPU does not reorder writes
//prevent compiler from reordering writes
asm volatile("":::"memory");
m_write++;
return true;
}
{
while(true)
{
//use a constant m_read each loop
//empty
return false;
return true;
}
}
private:
std::unique_ptr<T[]> m_array;
uint32_t m_write;
};


This line seems really strange to me:

static_assert(N!=0x80000000,"N is too large.");


Technically, it is rather odd to just compare for equality with one big number where there could be numbers even bigger. Didn't you mean:

static_assert(N >= 0x80000000, "N is too large.");


const uint32_t MASK = 2*N-1;


Since all the values in this line are known at compile time and MASK is apparently not meant to be changed, you should consider making it both static and constexpr:

static constexpr uin32_t MASK = 2*N-1;


That's kind of trivial, but you can also use curly braces instead of parenthesis in your constructor initialization list:

RnW1FifoFixed():
m_array{new T[N]},

• @Bob65536 But now you say it, it makes sense. And it's true that you already check for a power of 2 :) – Morwenn Mar 21 '14 at 18:22