如何在类的不同实例之间共享互斥对象
How do you share a mutex among different instances of a class?
我想知道如何在一个类的不同实例之间共享一个类中的互斥对象。
现在,我有一个类Indexer,它有一个Boost互斥和condition_variable作为私有成员变量。我在main中创建了Indexer类的auto_ptr,并将Indexer的指针传递给另一个类Robot的实例。
我喜欢这样做:
std::auto_ptr<Indexer> index_service(new Indexer());
Robot a(*index_service.get());
Robot b(*index_service.get());
Robot c(*index_service.get());
机器人的构造函数是:
Robot(Indexer &index_service)
{
this->index_service = index_service;
}
机器人的头部看起来像:
class Robot
{
public:
Robot(Indexer &index_service);
private:
Indexer index_service;
};
但是,由于互斥是不可压缩的,所以我得到了一个错误。
我想让互斥和condition_variable共享ptrs,但我读到这可能会导致意外行为。
有人能告诉我做这件事的正确方法吗?
谢谢!
我不是C++大师,但引用传递和指针的混合似乎很麻烦。
具体来说:this->index_service = index_service;
但该值作为Indexer &index_service
传入由于本地index_service类型为Indexer index_service;
我认为这项任务意味着抄袭。
我假设您只想要Indexer
的一个实例,所以您实际上是想在Robot类中存储对它的引用。要做到这一点,您需要让您的构造函数获取一个指针(无论如何,*index_service.get()
调用都会得到这个指针)。此外,您还希望类变量是指针类型。
在类中声明一个静态boost::mutex。记得在.cpp文件中定义它。
点击此处:在类中使用静态互斥
正如另一个选项一样,您可以使用std::shared_ptr
代替std::auto_ptr
,并在Robot
类中更改Indexer to
std::shared_ptr`。
class Robot
{
public:
Robot( std::shared_ptr<Indexer> const &index_service)
{
this->index_service = index_service;
}
private:
std::shared_ptr<Indexer> index_service;
};
std::shared_ptr<Indexer> index_service(new Indexer());
Robot a(*index_service.get());
Robot b(*index_service.get());
Robot c(*index_service.get());
相关文章:
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- C++两个源文件之间共享的枚举的静态实例
- 线程之间的实时数据共享
- 共享库 (.so) 没有扩展名的 Linux 可执行文件之间的区别?
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- Directx 12 :在两个进程之间共享图形内存
- 子目录之间的 CMAKE 共享变量
- C++ 多个 DLL 之间的共享接口
- 如何在进程之间共享大量数据而不重复?(国际刑罚委员会)
- 简单使用 std::atomic 在两个线程之间共享数据
- C++:在另外两个对象之间共享一个对象
- 在C++中的程序之间共享指针
- 拥有或在对象之间共享资源
- 在两个结构之间共享数组
- 如何在不同的CMakeList.txt之间共享变量?
- 在QT中的两个窗口之间共享websocket连接
- 在VS2017中,我们如何在项目成员之间共享编译设置
- 通过require在不同的Lua状态之间共享全局变量