Reputation: 13
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
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
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