gpt4 book ai didi

c++ - 正在访问指针元组的元组和线程安全的互斥锁

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

给定std::tuple

using Tuple1 = std::tuple<Foo1*, Bar1*, std::shared_ptr<std::mutex>>;
using Tuple2 = std::tuple<Foo2*, Bar2*, std::shared_ptr<std::mutex>>;
std::tuple<Tuple1, Tuple2> tuple;

还有函数,

void baz()
{
auto tup = std::get<0>(tuple);

std::lock_guard<std::mutex> lk(*std::get<2>(tup));

// Do something with std::get<0>(tup) and std::get<1>(tup)
}

根据 this 关于 SO 访问 std::tuple 的问题本质上不是线程安全的,但是在示例代码的情况下呢?是否有可能发生未定义/奇怪的事情?

这是假设 FooNBarN 仅在锁定后才被访问。

最佳答案

引用您所链接问题的完美答案:

However, if the parameter were const, then get would not be considered to provoke a data race with other const calls to get.

这基本上就是您的答案。 const 元组进行每次 get 调用(在任何未完全受互斥锁保护的元组上),您安全。

这意味着您发布的代码不安全。像这样修改:

void baz()
{
// vvvv just being explicit here
auto const & tup = std::get<0>(static_cast<decltype(tuple) const &>(tuple));

std::lock_guard<std::mutex> lk(*std::get<2>(tup));

// Dereference std::get<0>(tup) and std::get<1>(tup),
// use the pointed to objects at will, nothing else

// Not ok, because it could interfer with the call in initialisation of tup of another thread
// auto non_const_tup = std::get<0>(tuple)
}

目前我看到的唯一解决方案是使用像这样的元组:

std::tuple<
std::shared_pointer<std::mutex>,
std::unique_pointer<std::tuple<Foo1*, Bar1*>>
// Mutex and pointer to tuple for Foo2 and Bar2
>

所需的 const 将坚持一切(指针目标除外)。

关于c++ - 正在访问指针元组的元组和线程安全的互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44526371/

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