C使库适应多线程
发布时间:2020-12-16 07:28:33 所属栏目:百科 来源:网络整理
导读:我正在使用libconfig和线程来制作一个小型服务器应用程序.重点是,libconfig++ is not thread safe,所以我的想法是创建另一个类作为包含Mutex的包装器,类似这样: class app_config {public: app_config(); /* Here be my problems. */ void set(); void get(
我正在使用libconfig和线程来制作一个小型服务器应用程序.重点是,libconfig++ is not thread safe,所以我的想法是创建另一个类作为包含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 supports plenty of types的变量.那就是当我们的主角(我)发现自己正在寻找任何一位善良的心灵的C大师时,他愿意向他展示任何方式来实现这一目标. 本质上,get和set函数需要一个std :: string或一个char * path变量,其中包含配置文件变量的路径(我不介意使用)和返回类型(或者set的情况下的第二个参数) )应该有所不同…… 一如既往,任何帮助将不胜感激. 朱利安 解决方法
你也可以使用这种方法.我认为更难以错过,因此更优越. 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |