gpt4 book ai didi

c++ - std::unique_lock::release 的用例是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:17 29 4
gpt4 key购买 nike

在什么情况下会使用 std::unique_lockrelease 方法?我错误地使用了 release 方法而不是 unlock 方法,我花了一段时间才明白为什么下面的代码不起作用。

#include <mutex>
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

std::mutex mtx;

void foo()
{
std::unique_lock<std::mutex> lock(mtx);
std::cout << "in critical section\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
lock.release();
}

int main()
{
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i)
threads.push_back(std::thread(foo));

for (std::thread& t : threads)
t.join();
}

最佳答案

它在 this answer 中有很好的用途其中锁定状态的所有权明确地从函数本地 unique_lock 转移到外部实体(通过引用 Lockable 参数)。

这个具体示例是典型的用法:将锁定状态的所有权从一个对象(甚至类型)转移到另一个对象。

关于c++ - std::unique_lock::release 的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491075/

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