RAII:循环中声明的向量中的互斥体是否在下一次迭代中全部解锁?
假设我有以下问题:
// ... 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?
}
}
}
一个简单的问题,在代码本身中阐明。 locks_arr
中的互斥锁是否会在循环的下一次迭代中解锁,或者是否明确需要在 if
语句块中一一解锁所有互斥锁,在外部 for 循环的末尾?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回答我自己的问题——是的,这就是 RAII 的工作原理。该向量在 for 循环体内声明;它在每次迭代中都会被销毁并重新创建。
continue
还会导致循环其余部分的执行被短路。当向量被破坏时,它包含的每个对象也会被破坏。因此,
unique_lock
的析构函数被调用,这会解锁互斥锁。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.