C++为多线程调整库
C++ adapting a library for multithreading
我正在使用libconfig++和线程来制作一个小型服务器应用程序。重点是,libconfig++不是线程安全的,所以我的想法是创建另一个类,它充当Mutex的包装器,类似于这样:
class app_config {
public:
app_config();
/* Here be my problems. */
void set();
void get();
virtual ~app_config();
private:
Config cfg;
boost::mutex *cfg_mutex;
};
现在,这一切都很好,直到我意识到libconfig支持其变量的大量类型。当我们的主人公(我)发现自己在寻找任何一位心地善良的C++大师时,他愿意向他展示任何实现这一目标的方法。
从本质上讲,get
和set
函数需要一个std::string
或char*
path
变量,其中包含配置文件变量的路径(我不介意使用任何一个),并且返回类型(或set
的第二个参数)应该不同。。。
一如既往,我们将不胜感激。
Julian
您也可以使用这种方法。我认为它更难误用,因此更优越。Libconfig实例是包装器内部的私有成员,没有锁就无法访问。
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/shared_ptr.hpp>
class Libconfig {
public:
int Get(const char*) { return 0; }
};
class LibConfLock;
class LibconfMultithreadingWrapper {
friend class LibConfLock;
public:
LibconfMultithreadingWrapper()
:m_Libconfig(new Libconfig())
,m_Mutex(new boost::mutex())
{}
private:
boost::shared_ptr<Libconfig> m_Libconfig;
boost::shared_ptr<boost::mutex> m_Mutex;
};
class LibConfLock {
public:
LibConfLock(const LibconfMultithreadingWrapper& wrapper)
:m_Libconfig(wrapper.m_Libconfig)
,m_Mutex(wrapper.m_Mutex)
,m_Lock(new LockType(*m_Mutex))
{}
Libconfig& GetLibconf() const { return *m_Libconfig; }
private:
typedef boost::lock_guard<boost::mutex> LockType;
boost::shared_ptr<Libconfig> m_Libconfig;
boost::shared_ptr<boost::mutex> m_Mutex;
boost::shared_ptr<LockType> m_Lock;
};
int main() {
LibconfMultithreadingWrapper wrapper;
int i = LibConfLock(wrapper).GetLibconf().Get("hallo");
return i;
}
您可以编写一个装饰器类,将所有函数调用转发到私有libconfig实例。这意味着您需要将要使用的所有函数添加到装饰器中。另一种可能性是将对libconfig的调用转发给执行实际锁定的类。
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/bind.hpp>
class MultithreadingWrapper {
public:
template <class V, class T>
V ExecuteThreadSaveWithReturn(T func) {
boost::lock_guard<boost::mutex> l(m_Mutex);
return func();
}
template <class T>
void ExecuteThreadSave(T func) {
boost::lock_guard<boost::mutex> l(m_Mutex);
func();
}
private:
boost::mutex m_Mutex;
};
void f() {}
void f(int) { }
int f(int, int) { return 0; }
int main() {
MultithreadingWrapper wrapper;
wrapper.ExecuteThreadSave(boost::bind(f));
wrapper.ExecuteThreadSave(boost::bind(f, 1));
int i = wrapper.ExecuteThreadSaveWithReturn<int>(boost::bind(f, 1, 1));
return i;
}
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 多线程比没有线程C++慢
- 具有 C++11 多线程的特征库
- 矢量自动调整大小在多线程代码中是否是一种危险情况
- C++为多线程调整库
- vector多线程同步,一个读一个写:只在调整大小时锁定