Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c++ - Timing of scope-based lock guards and return values

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...