Home > OS >  how to write copy constructor in thread safe class c
how to write copy constructor in thread safe class c

Time:04-10

template<typename T>
class TSQueue {
public:
    TSQueue() {}
    TSQueue(const TSQueue& rhs) {
        lock_guard<mutex> lg1(rhs._mutex);
        _data = rhs._data;
    }

private:
    queue<shared_ptr<T> > _data;
    mutex _mutex;

};

I have seen in textbooks that only source (rhs) is locked in copy constructor. I am not sure how exclusive access of destination (this) is ensured by only locking rhs. I think both source and destination should be locked. What is the ideal way to write thread safe copy constructor?

CodePudding user response:

When the constructor runs it's creating a new object; there is no possibility of that object being accessed from another thread, because there is no code that can pass that (currently non-existent) object to another thread. So there's no need to protect the object that's being constructed.

CodePudding user response:

Let's step out of the C world for a bit. The objective is to copy something say a blueprint of a house at a given time. When the copy happens we do not want the architect to be modifying the blueprint. So we go ahead and lock the blueprint. Once we know it's safely locked away from any modification we copy the blueprint.

Now maybe not just you but several others also want a copy of the blueprint. So we ensure that the architect does not modify the blueprint whenever a copy is done.

Do we really care if you or the others modify their own copy while they are creating it. No we don't. All that matters is the source not the destination.

You as the owner of your copy are still in the process of creating it and so no one else would even be able to access it when you are still creating your copy.

Try translating this to the copy constructor code you have written and you will see why protecting the destination is not necessary

  • Related