Mutexes and lambda functions in C ++

When dealing with concurrency issues, I often use std::unique_lock<std::mutex>and std::lock_guard<std::mutex>, without problems with both.

I also expanded std::mutexto use it as follows:

mutex.protect([](){
    // my protected code here
}) ;

It blocks the mutex and releases it around the lambda call.

Is this similar behavior already implemented inside boost or the standard library?

+4
source share
2 answers

Boost Thread has the following: http://www.boost.org/doc/libs/1_58_0/doc/html/thread/synchronization.html#thread.synchronization.with_lock_guard

You can use it as you would expect:

std::mutex mx;

boost::with_lock_guard(mx, []{
    // protected stuff
});

INVOKE:

int foo(int,double) { return 42; }

// ...

int answer = boost::with_lock_guard(mx, foo, 3, 3.14);

​​ :

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)...);
    }

- , .

+5

, , , , . , , , , .

double process_func() { 
// do some stuff
    { //start a new scope block
      std::lock_guard<my_mutex> g; // mutex is locked here.
      []() { } // your lambda that needs to be protected
    } // Mutex is released here.
// do more stuff
} 

, , . - , , .

+1

Source: https://habr.com/ru/post/1625321/


All Articles