c++ - 从 std::tuple of double 的 std::vector 读取线程安全?

标签 c++ c++11 concurrency thread-safety stdvector

考虑一个包含以下 vector 的类:

std::vector<std::tuple<double, double, double> > _data;

和以下成员函数:

inline double second(const unsigned int i) const
{
    return std::get<1>(_data[i]);
}

我能保证这个函数是线程安全的吗(注意我返回了一个 double 的拷贝)?

如果不是,这个函数的线程安全版本是什么?

最佳答案

如果 std::vector 可以被另一个线程修改,这不是线程安全的。为了使其线程安全,必须同步对 std::vector 的访问。一个可能的解决方案是引入一个 std::mutex并将其与 std::vector 实例相关联。在这种情况下,std::mutex 将是包含 std::vector 的类的成员变量:

#include <mutex>

class X
{
private:
    std::vector<std::tuple<double, double, double>> data_;
    mutable std::mutex data_mutex_;
public:
    double second(const unsigned int i) const
    {
        // Note that 'operator[]' is not bounds checked.
        // Recommend adding a check to ensure 'i' is
        // within range or use 'at()'.

        std::lock_guard<std::mutex> lk(data_mutex_);
        return std::get<1>(data_[i]);
    }
};

注意 std::mutex 的添加使得类不可复制,因为它本身是不可复制的。

关于c++ - 从 std::tuple of double 的 std::vector 读取线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222529/

相关文章:

c++ - 将 std::map 作为默认参数传递

c++ - 通过引用返回静态 vector 很慢

android - 3个高频运行的线程使用相同的变量

java - 重用 Runnable 的最佳方式

c++ - SFINAE成员函数存在性测试问题

c++ - Cygwin GCC 与 Visual Studio 库链接

c++ - 使用快速排序对可能包含无穷大的容器进行排序是否安全?

c++ - 如何找到参数包的长度?

c++ - 带有 MinGW 4.8 的 Windows 上的模板 undefined reference

java - 并行运行多个 JPA 事务