• 0 Posts
  • 1 Comment
Joined 1 year ago
cake
Cake day: June 16th, 2023

help-circle

  • std::lock_guard and it’s superior alternative std::scoped_lock both deliberately cannot be moved, so you won’t be able to make it work with these types. But, assuming foo will cause the lambda to be destroyed once it is done executing you can use the more flexible std::unique_lock and move that into the lambda:

    std::unique_lock lock(my_map);
    my_map[p].insert(10);
    foo(bar1, [&my_map, l = std::move(lock)] (const auto& p) {
          my_map[p].insert(10);
    });
    

    If the lambda does not capture anything whose destructor could call code that tries to lock this same mutex by value and foo destroys the lambda immediately after the lambda has finished executing then this does exactly what you want.