简体   繁体   中英

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 . 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. 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

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 .

as per explained by CoryKramer in shared_mutex explanation

It fits your situation much better than std::mutex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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