bana
bana

Reputation: 397

Reference counting of the object in multithreaded application c++

I am trying to implement the reference count for the objects in a multithreaded program, so that I can delete the object when none of the threads wants to use it, or someone initiates the object delete.

For that I am doing the following:

class refCount{
    int ref_count;

    public:
        void incr_ref_count(){
        ref_count ++;
    } 

    int decr_ref_count(){
        ref_count--;
        return ref_count; 
    }

}

And am using the following code whenever I copy the obj in different threads:

pthread_mutex_lock(&ref_count_lock);
if(obj != NULL){
    dup_obj = obj;
    obj.incr_ref_count(); 
}
pthread_mutex_unlock(&ref_count_lock); 

and while removing the reference

pthread_mutex_lock(&ref_count_lock);
if(dup_obj != NULL){
    count = dup_obj.decr_ref_count(); 
    if(count == 0)
        delete dup_obj
}   
pthread_mutex_unlock(&ref_count_lock);

I was hoping it would work fine, but the problem I think I have is in using the mutexs(Lock), I need to have a mutex(Lock) for each object I create separately, so that I can make copying, and increasing or decreasing the count, to be atomatic. How to implement this?

Please note its not exactly a working code its kinda sudo code.

thanks for all the help.

Upvotes: 1

Views: 1516

Answers (2)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18158

Locks kill reference-counting performance. See for example Atomic Reference Counting Pointers for ways to reduce or eliminate the number of locks needed.

Upvotes: 3

dthorpe
dthorpe

Reputation: 36102

You don't necessarily need a separate lock object for every object instance you want to protect. If you use one lock object for all object instances, that will guarantee that only one thread at a time can manipulate the reference count. Having multiple lock objects would merely reduce the frequency of thread blocking.

Upvotes: 1

Related Questions