Hello,
I am trying to iterate over a list, a list that is contained
inside of a container class (call it MyContainer for now). This
container class has a public interface that allows clients of the
class to iterate over the list via two methods: GetFirstItem and
GetNextItem. Since this class is access from multiple threads, how
would I go about making the access thread-safe over multiple function
calls? These two calls go together and internally, they share the
same iterator for iterating the list. I know how to apply a critical
section to the code, however, only to one method at a time. I need to
distribute the access to this container class to only one thread at
time while making use of the GetFirstItem / GetNextItem combination.
I could setup a critical section in the GetFirstItem method, however,
this does not buy me much as the time elapsed between the invocations
of GetFirstItem and GetNextItem could allow for another thread to
change the value of the internal iterator.
The section of the container class relative to this topioc is as
follows:
/// .h
class MyContainer
{
public:
...
Item* GetFirstItem();
Item* GetNextItem();
private:
std::vector<Item*> m_ItemVec;
std::vector<Item*>::iterator m_ItemItr;
};
/// .cpp
Item* MyContainer::GetFirstItem()
{
m_ItemItr = m_ItemVec.begin();
return GetNextItem();
}
Item* MyContainer::GetNextItem()
{
Item* pItem = 0;
if (m_ItemItr != m_ItemVec.end())
{
pItem = (*m_ItemItr);
m_ItemItr++;
}
return pItem;
}
I somehow need to allow exclusive access across these two calls.
Any help would be greatly appreciated.
Michael