问题
class C {
mutable std::mutex _lock;
map<string,string> deep_member;
public:
auto get_big_lump()
{
std::unique_lock<std::mutex> lock(_lock); // establish scope guard
return deep_member; // copy the stuff while it can't be changed on another thread.
}
};
What is the guaranteed timing with respect to the guard and the copying of the return value? Will the copy take place while the lock is held, or can some of it be done after the function body returns, in the case of allowed (or actual!) optimizations?
回答1:
All destructor of local objects are called after the function body terminates. Return statement is a part of a function body, so it is guaranteed the lock will be held while the copy is performed.
Optimizations will not change this fact, they will only change the destination for the copy - it could either be an intermediate temporary or the real destination on the call site. The lock will only exist for the first copy, no matter where it is being sent to.
However, please keep in mind the the actual scope lock in the code is not correct. You need lock_guard
- but it is possible it is simply a demo copy-paste error and real code has real guard in place.
回答2:
std::lock
does not establish a scope guard! It only locks. It does not unlock. You want this:
std::unique_lock<std::mutex> lock(_lock);
which locks on construction and unlocks on destruction (which occurs on scope exit).
The initialization of the return value will occur before local variables are destroyed, and hence while the lock is held. Compiler optimizations are not allowed to break correctly synchronized code.
However, note that if the return value is then copied or moved into some other variable, this second copy or move will occur after the lock is released.
来源:https://stackoverflow.com/questions/34731298/timing-of-scope-based-lock-guards-and-return-values