[cpp-threads] RE: volatile, memory models, threads

Peter Dimov pdimov at mmltd.net
Sun Mar 5 13:18:47 GMT 2006


Peter Dimov wrote:

> class X
> {
> private:
>
>    T * pt_;
>
>    static T * init_pt( /* args */ )
>    {
>        return new T( /*args */ );
>    }
>
> public:
>
>    void f()
>    {
>        assign_pointer_once( pt_, init_pt, /*, args */ );
>
>        // use *pt_
>    }
> };

Now that I think of it...

The retry loop in assign_pointer_once will have to know how to dispose of 
the return value of init_pt.

template<class T, class F> void assign_pointer_once( T * & pt, F f )
{
    for( ;; )
    {
        if( atomic_load_acq( &pt ) != 0 ) break;

        T * p2 = f();

        if( atomic_compare_exchange_rel( &pt, 0, p2 ) ) break;

        delete p2;
    }
}

This means that the above should probably work on std::auto_ptr for type 
safety reasons. Which in turn means that it probably has to be a member of 
auto_ptr in order to access its private pointer.

So:

class X
{
private:

   std::auto_ptr<T> pt_;

public:

   void f()
   {
       pt_.create_once( /* args */ );
       // use *pt_
   }
};

:-)




More information about the cpp-threads mailing list