简体   繁体   English

将互斥锁与shared_ptr结合使用可保护跨副本共享的数据

[英]Using a mutex in conjunction with shared_ptr to protect data shared across copies

I have a class whose copies share the same data via shared_ptr . 我有一个类,其副本通过shared_ptr共享相同的数据。 Since that data is going to be modified by different threads I'm going to use a mutex in order to protect it, however, it is my understanding that the mutex object has to be the same across different copies in order to work, ignoring the fact that mutexes are not actually copyable. 由于该数据将由不同的线程修改,因此我将使用互斥锁来保护它,但是,据我了解,互斥对象在不同副本之间必须相同才能正常工作,而忽略了互斥体实际上不可复制的事实。

Therefore I intend to put the mutex into a shared_ptr as well. 因此,我也打算将互斥锁放入shared_ptr中。 Like so: 像这样:

#pragma once

#include <mutex>
#include <memory>
#include <vector>

class test {
public:
  auto some_action(int x) -> void {
    std::scoped_lock(*m_store_mutex);

    m_shared_store->push_back(x);
  }

private:
  std::shared_ptr<std::mutex> m_store_mutex { std::make_shared<std::mutex>() };
  std::shared_ptr<std::vector<int>> m_shared_store { std::make_shared<std::vector<int>>() };
};

Is this approach valid? 这种方法有效吗? It seems to be working but I'd like to be sure. 它似乎正在工作,但我想确定。

PS PS

This question is fairly similar to mine, but I do not feel like the answers are quite specific enough. 这个问题与我的非常相似,但是我觉得答案不够具体。

You may want to consider std::shared_mutex instead of std::mutex . 您可能需要考虑使用std::shared_mutex而不是std::mutex

as per explained by CoryKramer in shared_mutex explanation 根据CoryKramer在shared_mutex说明中的解释

It fits your situation much better than std::mutex . 它比std::mutex更适合您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM