在 2 个对象之间共享容器的提示
Tips to share container between 2 objects?
我有一些STL容器,我需要在2种不同类型的对象之间共享 - 比如A和B。容器在类 A 中定义,并在类 B 中用作引用。由于 STL 容器不是线程安全的,我计划在 A 中定义 boost::mutex
并将其作为引用存储在类 B 中。
这个计划显然失败了,因为我意识到boost::mutex
是不可复制的。我无法将容器移出类 A 或在容器上提供包装器。你会在这里做什么?
为什么不能复制互斥体?
我不是 100% 确定我可以遵循,但是如果您想在一个类的两个实例之间共享互斥锁以保护共享资源,为什么不只使用 boost::shared_ptr<boost::mutex>
从两个实例访问互斥锁?
当您需要共享资源时,这应该是一个通用策略,您也可以考虑将boost::shared_ptr
用于容器本身,但如果没有看到您的代码,很难提供一些具体的建议。
class Sample
{
std::vector<int> v;
private:
struct Mut;
};
struct Sample::Mut
{
boost::mutex mut_;
};
或
class Sample {
std::vector<int> v;
public:
boost::shared_ptr<boost::mutex> mutt;
Sample() : mutt(new boost::mutex) {}
};
现在,您可以在提供互斥包装器访问权限的其他对象中引用此示例的boost::mutex
,或者可以使用Mut
结构或boost::shared_ptr
的副本直接初始化这些对象。 boost::shared_ptr
是可复制的,它的所有副本都将共享给定的互斥锁。
为什么不能复制互斥体?
因为互斥锁是不可复制的。这是它派生自boost::noncopyable
:
#include <boost/thread/mutex.hpp>
class mutex:
boost::noncopyable
{
不可复制类是一个基类。 从中派生您自己的类 不可复制,当您想要禁止复制构造和复制时 分配。
事实上,您不需要它们的副本,因为它毫无用处,而是您希望在许多对象中共享相同的实例,并引用保护对单个资源的访问的单个互斥锁。
从<boost/noncopyable.hpp>
:
// Private copy constructor and copy assignment ensure classes derived from
// class noncopyable cannot be copied.
// Contributed by Dave Abrahams
namespace noncopyable_ // protection from unintended ADL
{
class noncopyable
{
protected:
#ifndef BOOST_NO_DEFAULTED_FUNCTIONS
BOOST_CONSTEXPR noncopyable() = default;
~noncopyable() = default;
#else
noncopyable() {}
~noncopyable() {}
#endif
#ifndef BOOST_NO_DELETED_FUNCTIONS
noncopyable( const noncopyable& ) = delete;
noncopyable& operator=( const noncopyable& ) = delete;
#else
private: // emphasize the following members are private
noncopyable( const noncopyable& );
noncopyable& operator=( const noncopyable& );
#endif
};
}
typedef noncopyable_::noncopyable noncopyable;
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 在cuda线程之间共享大量常量数据
- 如何从具有移动语义的类对象中生成共享指针
- 在c代码之间共享数据的最佳方式
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 将静态库链接到不带-fPIC的共享库中
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 使用Boost Interprocess创建托管共享内存需要很长时间
- 无法在Ubuntu上将共享库与Eclipse链接
- 从python调用openMP共享库时,未定义opnMP函数
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 为什么我的共享库中存在展开符号
- 使用共享指针的函数调用,其对象应为 const
- 具有两个独占锁组的共享锁
- 共享队列的线程安全
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 在Windows桌面共享API上,UAC提示变为黑色暂停屏幕
- 在 2 个对象之间共享容器的提示