Timing of scope-based lock guards and return values

情到浓时终转凉″ 提交于 2019-11-28 08:06:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!