186524857204
186524857204

Reputation: 13

c++ Lock class skeleton

From Effective STL (by Scott Meyers) Item 12, below is the skeleton of a c++ Lock class.

template<typename Container>
class Lock {
public:
    Lock(const Container& container)
    : c(container)
    {
        getMutexFor(c);
    }

    ~Lock()
    {
        releaseMutexFor(c);
    }
private:
    const Container& c;
};

The point I do not understand is why the mutex is acquired on the lock's c private member (itself copy-constructed from the container we want to take a lock on).

Will the following effectively lock v (and why)?

vector<int> v;
{
    Lock<vector<int> > lock(v);
    ...
}

Thanks.

Upvotes: 1

Views: 455

Answers (3)

juanchopanza
juanchopanza

Reputation: 227468

The point I do not understand is why the mutex is acquired on the lock's c private member (itself copy-constructed from the container we want to take a lock on).

c is a reference to the container passed to the lock's constructor, not a copy. So that very same container is getting locked.

Will the following effectively lock v (and why)?

vector<int> v;
{
    Lock<vector<int> > lock(v);
    ...
}

Yes, v will be locked in the scope defined by the {} (assuming the locking mechanism has been correctly implemented, of course.)

Note that this lock is only useful if all other code accessing v locks the same mutex, for example, by following the same convention of using the lock guard.

See also std::lock_guard.

Upvotes: 3

Mel Viso Martinez
Mel Viso Martinez

Reputation: 658

Effectively is a reference, so is the same object passed to the constructor as @juanchopanza says. Relative to the second question, "Will the following effectively lock v (and why)?" I think not. This is an example and Container must be a special class that holds a mutex. We need to see the rest of the code. But vector dont have, as long as I know, internal mutex locks.

Upvotes: 0

grzkv
grzkv

Reputation: 2619

The whole point is that c is not copy-constructed, it is a reference.

Upvotes: 0

Related Questions