Timing of scope-based lock guards and return value

2019-02-24 00:45发布

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?

标签: c++ scope rvo
2条回答
一纸荒年 Trace。
2楼-- · 2019-02-24 00:54

All destructor of local objects are called after the function body terminates. Return statement is a part of a function body, so it is guranteed 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 simly a demo copy-paste error and real code has real guard in place.

查看更多
贪生不怕死
3楼-- · 2019-02-24 01:12

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.

查看更多
登录 后发表回答