Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr and weak_ptr concurrency
From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2009-09-03 00:02:05


On Wed, Sep 2, 2009 at 1:18 AM, Rajeev Rao <rbsrao79_at_[hidden]> wrote:

> Thanks for the response. What if I place accesses to the global pointer
> within critical sections (indicated by mutex.lock()-unlock()) ? I've
> enclosed the dominant portions of the code in while loops. Does this make
> it thread safe ?
>
> <code>
>
> //initializion Thread (runs before any other thread):
> shared_ptr< MyClass > global_ptr(createNewObject()) ;
>
> //WriterThread :
>
> while(true) {
> mutex.lock()
> global_ptr.reset( createNewObject())
> mutex.unlock();
> sleep (5) ;
> }
>
>
By the way, to minimize contention, call createNewObject() outside the lock:
     local = createNewObject();
     lock();
     global = local;
     unlock();

>
> //ReaderThreads:
>
> mutex.lock()
> weak_ptr<MyClass> local_weak_ptr (globally_ptr) ;
> mutex.lock()
>
I assume you meant UNlock in that second mutex call above!

> ...
> while(true) {
> if(shared_ptr< MyClass > local_shared_ptr = local_weak_ptr.lock() ) {
> // using local_shared_ptr.
> } else {
> // recreate weak ptr from global ?
>
if you decide to recreate, you need to relock, of course.

> }
> } // end of while loop
>
> yep, that's the typical usage.
Tony



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