gpt4 book ai didi

c++ - 如何在这个条件下使用 lock_guard

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:46 26 4
gpt4 key购买 nike

一个线程有如下的控制流程:

mutex.lock()
if (condition) {
// do synced things
mutex.unlock();
// do parallel things
} else {
// do other synced things
mutex.unlock();
// do other parallel things
}

请注意这四个do 部分如何执行不同的事情。

如何将锁定和解锁的直接调用替换为使用 std::lock_guard

最佳答案

std::unique_lock 看起来像您要找的东西。语义类似于 std::lock_guard,但是 allows more sophisticated constructs .因此,在您的情况下,您仍然可以获得异常安全性,但也可以提前明确解锁。像这样的东西:

std::unique_lock<decltype(mutex)> guard(mutex); // calls mutex.lock() like lock_guard
if (condition) {
// do synced things
guard.unlock();
// do parallel things
} else {
// do other synced things
guard.unlock();
// do other parallel things
}
// unlocks on leaving scope, if held similar to lock_guard

关于c++ - 如何在这个条件下使用 lock_guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573750/

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