Friday, January 7, 2011

Differential Reference Counting

Just published an article on Differential Reference Counting - reference counting algorithm which provides strong thread-safety and permits useful use cases that are not permitted by plain atomic reference counting (like boost::shared_ptr).


  1. I guess this is not correct way to use the smart pointer.
    This does not differ from the variant with a regular global pointer, without any reference counting at all.

    T * ptr;

    // thread 1
    ptr->SomeMethod(); //The problem is the same - who is freeing it at this time?

    To use it properly, we have to increment the reference counter safely in the thread, who is already an owner of the resource :

    // thread 1
    shared_ptr ptr(new T);
    // now this thread is a sole owner of the resource

    // lets share it with another thread.
    shared_ptr ptr2 = ptr;// The counter was incremented in this thread - nobody could free it.

    CreateThreadWithContext(Thread2Func, ptr.get());

    // thread 2
    void Thread2Func(T * p)
    shared_ptr ptr(p, false);// false means NOT to increment reference counter again

    ptr->SomeMethod();// You can use it safely, You are already an owner, nobody can free it.

    }// destructor of shared_ptr decrement reference counter, and free the resource, if this thread is its last owner.

    It may be enough for safe life-time management.

    But your idea is interesting as a access point to some resource.

  2. > I guess this is not correct way to use the smart pointer.

    It's an incorrect way to use a reference counting algorithm, if it does not support such usage. However, if it does support such usage, then it's a correct usage.
    Btw, smart pointers are no more than a syntactic sugar.