gpt4 book ai didi

c++ - 将互斥量与 shared_ptr 结合使用以保护跨拷贝共享的数据

转载 作者:行者123 更新时间:2023-11-28 04:19:31 25 4
gpt4 key购买 nike

我有一个类,其拷贝通过 shared_ptr 共享相同的数据。由于该数据将被不同的线程修改,我将使用互斥体来保护它,但是,据我了解,互斥体对象必须在不同的拷贝中相同才能工作,忽略事实上,互斥体实际上是不可复制的。

因此我打算将互斥量也放入 shared_ptr 中。像这样:

#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>>() };
};

这种方法有效吗?它似乎有效,但我想确定一下。

附言

This问题与我的非常相似,但我觉得答案不够具体。

最佳答案

您可能需要考虑 std::shared_mutex 而不是 std::mutex

根据 CoryKramer 在 shared_mutex explanation

它比 std::mutex 更适合您的情况。

关于c++ - 将互斥量与 shared_ptr 结合使用以保护跨拷贝共享的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com