Hi all,
I'm currently thinking about how to make a thread safe queue. Specified as such:
- Single reader
- Multiple writers
- Dynamically sized
- Suitable for both a reader sleeping on a queue or as a polled queue
So what I'm looking at so far (pseudo)code wise is the following
#define unsigned long u32_t;
struct stElement
{
u32_t size;
u32_t* pData;
};
class clTSQueue
{
public:
void SetSleepSignal( signal* _signal); /* signal so the reader can sleep on this Q */
void Push( stElement* _element );
stElement* Pop( void );
u32_t GetNumElements( void ); /* if not sleeping on the queue will definitely want to know this */
protected:
std::list<stElement*> m_elements;
mutex m_hMutex;
signal* m_pSignal;
};
void clTSQueue::Push( stElement* _element )
{
/* make a copy of the data passed in */
stElement* cpOfElem = new u32_t[_element->size];
memcpy(cpOfElem->data, _element->data, _element->size);
cpOfelement->size = _element->size;
mutex_lock( m_hMutex ); /* lock the resource */
m_elements.push_back( cpOfElem ); /* append the new copy to the queue */
if( NULL != m_pSignal ) /* if we have a valid signal then signal it */
{
set_signal( m_signal );
}
mutex_unlock( m_hMutex ); /* unlock the resource */
}
stElement* clTSQueue::Pop( void )
{
return m_elements.pop_front();
}
This brings me to the question at hand then. Is having a write lock enough as only one reader reading from the front of the queue should not interfere with writers? or is that a misplaced way of thinking?
If anyone can give any advice, opinions or improvements on this mock up code then I would really appreciate it.
many thanks
Kano