I am currently trying to stream a multi-threaded program with a single thread. This software makes heavy use of refCounted objects, which lead to some problems in multithreaded mode. I am looking for some kind of design template or something that can solve my problem.
The main problem is deleting the object between the threads, usually deleting only decreases the reference count, and when refcount is zero, the object is deleted. This works well in a monochrome program and allows you to achieve large performance improvements with a copy of a large object.
However, in multithreaded mode, two threads may want to delete the same object at the same time, since the object is protected by the mutex, only one thread deletes the object and blocks the other. But when it frees the mutex, another thread continues execution with an invalid (freed object), which leads to memory corruption.
Here is an example with this RefCountedObject class
class RefCountedObject { public: RefCountedObject() : _refCount( new U32(1) ) {} RefCountedObject( const RefCountedObject& obj ) : _refCount( obj._refCount ) { ACE_Guard< ACE_Mutex > guard( _refCountMutex ); ++(*_refCount); } ~RefCountedObject() { Destroy(); } RefCountedObject& operator=( const RefCountedObject& obj ) { if( this != &obj ) { Destroy(); ACE_Guard< ACE_Mutex > guard( _refCountMutex ); _refCount = obj._refCount; ++(*_refCount); } return *this; } private: void Destroy() { ACE_Guard< ACE_Mutex > guard( _refCountMutex );
Suppose that two threads want to delete the same RefCountedObject, both are in ~ RefCountedObject and call Destroy (), the first thread has blocked the mutex and the other is waiting. After deleting the object on the first thread, the second will continue to execute and will call up free memory.
Does anyone have experience with a similar problem and find a solution?
Thank you all for your help, I understand my mistake: Mutex only protects the refCount pointer, not the refCount! I created the RefCount class, which is protected by a mutex. Mutex is now shared among all refCounted objects.
Now everything is working fine.
c ++ multithreading design
Steve gury
source share