I want to return a std::vector
. This std::vector
may be accessed from other threads (read and write). How can I unlock my std::mutex
just
Use a std::lock_guard to handle locking and unlocking the mutex
via RAII, that is literally what it was made for.
int foo()
{
std::lock_guard lg(some_mutex); // This now locked your mutex
for (auto& element : some_vector)
{
// do vector stuff
}
return 5;
} // lg falls out of scope, some_mutex gets unlocked
After foo
returns, lg
will fall out of scope, and unlock
some_mutex
when it does.