C ++使库适合多线程 [英] C++ adapting a library for multithreading

查看:62
本文介绍了C ++使库适合多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用libconfig ++和线程来制作小型服务器应用程序.关键是, libconfig ++不是线程安全的,所以我的想法是创建另一个充当互斥对象包装器的类,如下所示:

I'm working with libconfig++ and threads for making a small server application. The point is, libconfig++ is not thread safe, so my idea is to create another class which acts as a wrapper with a Mutex, something like this:

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 ++专家时,他会以一种善良的心愿意向他展示任何使它工作的方法.

Now, this is all good until I realize that libconfig supports plenty of types for its variables. And thats when our protagonist (me) finds himself in search of any C++ guru with a kind heart willing to show him any way to get this working.

从本质上讲,getset函数将需要一个std::stringchar* path变量,其中包含配置文件变量的路径(我也不介意使用其中任何一个)和返回类型(或set情况下的第二个参数)应该有所不同...

Essentially, the get and set functions would need a std::string or a char* path variable containing the path to the configuration file's variable (I wouldn't mind using either) and the return type (or the second argument in the set's case) should vary...

一如既往,我们将不胜感激.

As always, any help will be appreciated.

朱利安

推荐答案

您也可以使用这种方法.我认为滥用更困难,因此也很出色. Libconfig实例是包装器内部的私有成员,没有锁就无法访问.

You could as well use this approach. I think it more difficult to missuse and therefore superior. The Libconfig instance is a private member inside of the wrapper and can't be accessed without a lock.

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

这篇关于C ++使库适合多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆