How to std::mutex::lock until function returns

前端 未结 2 2043
忘了有多久
忘了有多久 2021-02-20 08:42

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

2条回答
  •  星月不相逢
    2021-02-20 09:20

    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.

提交回复
热议问题