gpt4 book ai didi

c++ - 在循环中使用 lock_guard

转载 作者:太空狗 更新时间:2023-10-29 21:13:49 24 4
gpt4 key购买 nike

我有一个数组,其中每个条目都是一个链表。为了避免在访问链接列表时出现同步问题,我为每个条目添加了一个互斥量。

我的问题是,我能否将循环的每次迭代中对 lockunlock 的以下调用转换为一个 lock_guard ,如下所示?每次迭代后是否会解锁每个条目的互斥量?谢谢。

for(int i = 0; i < TABLE_SIZE; ++i)
{
table[i].entryMtx.lock ();

//... access the linked list of the entry...

table[i].entryMtx.unlock ();
}

// --->

for(int i = 0; i < TABLE_SIZE; ++i)
{
std::lock_guard < std::mutex > lk (table[i].entryMtx);

// ... access the linked list of the entry
}

最佳答案

是的,这就是 C++(和其他语言)中析构函数的使用方式。

但是,它不是stdx,而是std。可能是打字错误。

关于c++ - 在循环中使用 lock_guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com