Subj : Re: stl & threads To : comp.programming.threads From : Uenal Mutlu Date : Tue May 24 2005 01:25 pm "Lyonya" wrote > have anybody here tried c++'s stl with threads? any > pitfalls/problems/tips? maybe a book/paper to read? Here are the ingredients: You should make each object you want to share (ie. use) among multiple threads 'lockable'. I recommend to add a mutex to each such object by using constructs like those below: class mutex { public: mutex(bool AfRecursiveMutex = true); ~mutex(); void Lock(); void Unlock(); bool IsLockedByAny() const; bool IsLockedByMe() const; // ... }; And by using the following you can extend any object with a default contructor to a 'Lockable' object, for example all STL containers: template class Lockable : public T { public: mutex mx; // a mutex for the object Lockable() {} private: Lockable(const Lockable&); // copy ctor: prohibit copying }; Then, in applic code one would use something like the following automatic helper object to do the actual locking/unlocking: class Locker { public: Locker(mutex& Amx) : mx(Amx) { mx.Lock(); } ~Locker() { mx.Unlock(); } private: mutex& mx; }; Example usage: Lockable > vec; void* thrprocA(void* Ap) { Locker L(vec.mx); // it is safe to modify vec } void* thrprocB(void* Ap) { Locker L(vec.mx); // it is safe to modify vec } For a standard implementation of a recursive (and also non-recursive) mutex under Windows see the following in the Win32 API: CRITICAL_SECTION, InitializeCriticalSection(), DeleteCriticalSection(), EnterCriticalSection(), LeaveCriticalSection() A faster alternative is to use atomic counters. A description and code for this you can find on the page of John M. Dlugosz : http://www.dlugosz.com/Repertoire/refman/Classics/atomic_counter_whitepaper.html Futher links: http://www.codeguru.com/Cpp/W-P/win32/tutorials/article.php/c9823/ http://zthread.sourceforge.net/ .