Boost logo

Boost Users :

From: Michael Marcin (mike.marcin_at_[hidden])
Date: 2008-07-14 11:48:03


I'm attempting to use boost thread's synchronization primitives to
implement an efficient resource repository.

The resource repository identifies immutable resources by an unique id.

If the resource is cached it just returns a shared_ptr to the resource.

If the resource is not yet loaded it does a potentially expensive
construction on the resource stores it in the cache and then returns a
shared_ptr to the resource.

Resources can potentially request other resources from the repository
during their construction so that case must be considered.

The single-threaded version of this class is fairly straightforward but
I don't have much experience in making things parallel so I'm
struggling. I was hoping someone could offer suggestions on how to make
an efficient multi threaded implementation.

Single threaded version below:

class ResourceStream;

class Repository
{
   typedef std::map< ResourceIdentifier,
     boost::weak_ptr<const void> > ResourceCache;
public:
   template< typename Resource >
   boost::shared_ptr<const Resource> Acquire( ResourceIdentifier id )
   {
      boost::shared_ptr<const Resource> resource;

      ResourceCache::iterator it = m_resourceCache.find(id);
      if( it != m_resourceCache.end() )
      {
         boost::weak_ptr<const void> cachedResource = it->second;
         try
         {
            resource = boost::shared_static_cast<const Resource>(
               cachedResource.lock() );
         }
         catch( boost::bad_weak_ptr& )
         {
         }
      }

      if( !resource )
      {
         resource.reset( new Resource( *this, Fetch(id) ) );
         m_resourceCache.insert(
           ResourceCache::value_type( id, resource ) );
      }

      return resource;
   }

private:
   // magic that retrieve an unprocessed resource based on an id
   ResourceStream Fetch( ResourceIdentifier id );

   ResourceCache m_resourceCache;
};

Thanks,

Michael Marcin


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net