如何使共享状态对象线程安全

时间:2017-01-18 10:11:07

标签: multithreading c++11 shared-ptr

我正在处理一个实现共享数据复制语义的类,这样对象的副本将在内部与原始对象共享相同的数据。

这个类本质上是一个带有一些便利访问器的std::shared_ptr的包装器。精简版将是:

class ControlParameters {

  using ControlsMap = std::map<std::string, float>;

public:
  ControlParameters() : controls_(std::make_shared<ControlsMap>()) {};
  ControlParameters(const ControlParameters& other) = default;
  ControlParameters& operator=(const ControlParameter& other) = default;
  ControlParameters(ChannelControlParameter&& other) = delete;
  ControlParameters& operator=(ControlParameter&& other) = delete;

  void setValue(float value, const std::string& key) const
  {
    auto& currentValue = (*controls_)[key];
    if (currentValue != value)
      currentValue = value;
  };

  float operator[](const std::string& key) const
  {
    return (*controls_)[key];
  };

private:
  std::shared_ptr<ControlsMap> controls_;
};

现在我意识到需要使类也是线程安全的,以确保原子读/写。请注意,在这种情况下,并发访问应该是来自不同线程和共享相同数据的不同实例的访问。我怎么能去做呢?

注意:我知道c ++ 17 shared_mutex可以满足我的目的,但我还不能使用c ++ 17的功能。

0 个答案:

没有答案
相关问题