Tech Support > Computers & Technology > Programming > Thread safe functionality over multiple method invocations in C++
Thread safe functionality over multiple method invocations in C++
Posted by Michael on October 8th, 2003


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

Posted by Corey Murtagh on October 8th, 2003


Michael wrote:

You could try a Lock/Unlock function pair that uses a Mutex or similar
to lock the list. When you want to access the list you call Lock, use
GetFirst and GetNext to iterate, then call Unlock. You could automate
this by having GetFirst call Lock, and call Unlock when GetNext hits the
end of the list or explicitly call Unlock when you're done with the list.

You probably will have to store the locking thread id and check it in
GetNext and Unlock just to make sure that another thread can't affect
the iterator, or Unlock it while you're iterating in another thread.

Unfortunately, thread-safety isn't as simple as it first seems.

--
Corey Murtagh
The Electric Monk
"Quidquid latine dictum sit, altum viditur!"



Similar Posts