Threading a Shared Model with pointers

Threading a Shared Model with pointers I have a vector of pointers to objects created with new. Multiple threads access this vector in a safe manner with get/set. However, a thread may delete one of the objects, in which case another thread's pointer to the object is no longer valid. How can a method know if the pointer is valid? I have to examples that work and would like your thoughts. Test for pointer validity: 1. Use integers instead of pointers. A hash (std::map) checks to see if the pointer is still valid. Public methods look like get(size_t iKey), etc. Insde the method it does: if((it = mMap.find(iKey)) != mMap.end()) { TMyType * pMyType = it->second; // do something with know good pointer. } 2. Have a vector of shared_ptr. Each thread tries to call lock() on its weak_ptr. If the returned shared_ptr is null we know someone deleted it while we were waiting. Public methods look like get(boost::weak_ptr<TMyType> pMyType), etc. Insde the method it does: boost::shared_ptr<TMyType> pGOOD = pMyType.lock(); if (pGOOD == NULL) { // null, bad pointer do something return; } 3. Test for null on plain raw pointers? Is this possible? Public methods look like get(TMyType * pMyType), etc. Option 1 and 2 actually seem to work well. I don't know how they will scale. What is the best approach? Is there a portable version 3?
participants (1)
-
pcunite@fsmail.net