Multithreading Issues
STL is not thread protected, so you must provide locks on your collections if
they will be used in multithreaded environment.
The standard locking mechanisms of Mutexes, Semaphores and Critical Sections can be used. One simple mechanism for providing locking is to declare a lock class. In this class the constructor creates the lock, and the destructor destroys the lock.
Then provide lock() and unlock() methods. For example:
class Lock
{
public:
HANDLE _hMutex; // used to lock/unlock object
Lock() : _hMutex(NULL)
{ _hMutex = ::CreateMutex( NULL, false,NULL) ); }
virtual ~Lock() { ::CloseHandle( _hMutex ); }
bool lock ()
{
if ( _hMutex == NULL )
return false;
WaitForSingleObject( _hMutex, INFINITE );
return true;
}
void unlock ()
{ ReleaseMutex(_hMutex); }
};
Then declare a class that is derived from one of the STL collections,
and in the class override the access methods to the collection that might cause an insertion or deletion of an element.
For example a general vector class would be:
template <class T>
class LockVector : vector<T>, Lock
{
public: LockVector () : vector<T>(), Lock() {}
virtual LockVector () {}
void insert ( T & obj )
{
if ( !lock())
return;
vector<T>::push_back (obj);
unlock();
}
};