Fal*_*lco 5 c++ lambda boost mutex c++11
当并发处理问题我经常使用std::unique_lock<std::mutex>,并std::lock_guard<std::mutex>与两者没有任何问题.
我也扩展std::mutex到能够使用它如下:
mutex.protect([](){
// my protected code here
}) ;
Run Code Online (Sandbox Code Playgroud)
它锁定互斥锁并在lambda调用周围释放它.
在boost或标准库中是否已经实现了类似的行为?
Boost Thread有这个:http://www.boost.org/doc/libs/1_58_0/doc/html/thread/synchronization.html#thread.synchronization.with_lock_guard
您可以像预期的那样使用它:
std::mutex mx;
boost::with_lock_guard(mx, []{
// protected stuff
});
Run Code Online (Sandbox Code Playgroud)
它甚至支持通常的INVOKE语义:
int foo(int,double) { return 42; }
// ...
int answer = boost::with_lock_guard(mx, foo, 3, 3.14);
Run Code Online (Sandbox Code Playgroud)
你可以自己轻松添加这样的东西:
template <typename M, typename F, typename... Args>
auto my_with_lock_guard(M& mx, F&& f, Args&&... args) {
std::lock_guard<M> lk(mx);
return std::forward<F>(f)(std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)
如果标准采用这样的提议,您可以轻松地将其交换出来.