RAII: do mutexes in a vector declared in a loop all unlock in the next iteration?

335 views Asked by At

Suppose I have the following:

// ... necessary includes

class X {
    struct wrapper{ std::mutex mut{}; }
    std::array<wrapper, 20> wrappers{};

    void Y() 
    {
        for (auto i{0u}; i < 10; ++i)
        {
            std::vector<std::unique_lock<std::mutex>> locks_arr{};
            for (auto& wrapp : wrappers)
            {
                locks.emplace_back(std::unique_lock{wrapp.mut});
            }

            // are the mutexes in locks_arr unlocked here by RAII,
            // because locks_arr goes 'out of scope'?
            if (/* some condition */) continue; 
            
            // do some other long stuff
            // end of loop iteration; how about here? 
        }
    }
}

A straightforward question, elucidated in the code itself. Do the mutex locks in locks_arr unlock in the next iteration of the loop, or is there an explicit need to unlock all the mutexes one by one in both the if statement block, and at the end of the outer for-loop?

1

There are 1 answers

0
SRSR333 On BEST ANSWER

To answer my own question—yes, this is how RAII works. The vector is declared inside the body of the for loop; it is destroyed and recreated every iteration. continue also causes the execution of the rest of the loop to be short-circuited.

When the vector is destructed, every object it contains is also destroyed. As such, the destructor of unique_lock is called, which unlocks the mutexes.