线程安全向量:此实现是线程安全的吗? [英] Thread-safe vector: Is this implementation thread-safe?

查看:75
本文介绍了线程安全向量:此实现是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对线程安全一词有疑问.让我举个例子:

I have a question regarding the term thread-safety. Let me give an example:

#include <mutex>
#include <vector>

/// A thread-safe vector
class ThreadSafeVector {
private:
  std::mutex m;
  std::vector<double> v;

public:
  // add double to vector
  void add(double d) {
    std::lock_guard<std::mutex> lg(m);
    v.emplace_back(d);
  }

  // return length of vector  
  int length() {
    std::lock_guard<std::mutex> lg(m);
    return v.size();
  }   
};

您会调用该类(即其所有方法)是线程安全的吗?

Would you call that class, i.e. all its methods, thread-safe?

编辑[美国东部标准时间星期日,晚上9点]

EDIT [Sunday, 9 PM CEST]

在获得一些好的是,但是"答案和替代实现之后,我在下面的答案中提供了自己的观点.基本上,它可以归结为一个简单的问题,即类的线程安全是否只需要为执行其方法的ALLALLEL提供强的原子性和可见性保证,或者类是否必须保证其自身范围之外的保证(例如SERIAL)执行).

After getting some good "yes, but"-answers and alternative implementations, I provided my own view in an answer below. Basically, it boils down to the simple question, whether thread-safety of a class only has to make strong atomicity and visibility guarantees for PARALLEL execution of its methods OR whether a class has to make guarantees that stretch beyond its own scope (for example SERIAL execution).

推荐答案

恕我直言:

这既安全又有用:

  void add(double d) {
    std::lock_guard<std::mutex> lg(m);
    v.emplace_back(d);
  }

这是安全的,但没用:

  // return length of vector  
  int length() {
    std::lock_guard<std::mutex> lg(m);
    return v.size();
  }   

由于时间长了,它可能已经改变了,因此对其进行推理不太可能有用.

Because by the time you've got your length it may well have changed, so reasoning about it is unlikely to be useful.

这个怎么样?

template<class Func>
decltype(auto) do_safely(Func&& f)
{
  std::lock_guard<std::mutex> lock(m);
  return f(v);
}

这样称呼:

myv.do_safely([](auto& vec) { 
  // do something with the vector
  return true;  // or anything you like
});

这篇关于线程安全向量:此实现是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆