I am using a CList in a multithreaded environment and I keep having problem with the GetHead method. I have one thread that add data to the list, and an other thread who read and remove data from the list.
Here is the reading part :
value_type get_next()
{
T t;
if(!queue.IsEmpty()) {
t = queue.GetHead();
}
return t; //If the queue is empty we return an empty element
}
Here is the inserting part :
inline void insert(T &_in)
{
queue.AddTail(_in);
}
Here is the removing part
inline void pop_next()
{
if(!queue.IsEmpty()) {
queue.RemoveHead();
}
}
Why do I get a runtime error when I run this. It always fail at
t = queue.GetHead();
With this assertion :
template<class TYPE, class ARG_TYPE>
AFX_INLINE TYPE& CList<TYPE, ARG_TYPE>::GetHead()
{ ENSURE(m_pNodeHead != NULL);
return m_pNodeHead->data; }
While the m_pNodeHead value is :
- pNext 0x00000000 {pNext=??? pPrev=??? data={…}
} CList > >,ATL::CStringT > > &>::CNode *- pPrev 0x00000000 {pNext=??? pPrev=??? data={…}
} CList > >,ATL::CStringT > > &>::CNode *- data “” TESTSETSE ATL::CStringT > >
You have a race condition between inserting and retrieving the value. Add a lock that includes the entire body of get_next(), insert(), and pop_next().