【cpprestsdk】浅谈cpprestsdk线程池及使用

cpprestsdk根据include文件夹可以看到共包含两部分内容:
1、pplx
2、cpprest

pplx/threadpool.h源代码中创建线程池有两种方式
1、通过construct接口创建,返回一个unique_ptr,由调用者控制线程池的生命周期
    _ASYNCRTIMP static std::unique_ptr __cdecl construct(size_t num_threads);
2、通过静态接口initialize_with_threads接口,创建了一个静态的线程池对象,结束生命周期为进程退出
    static void initialize_with_threads(size_t num_threads);

如果想使用使用其中的cpprest来创建http server或者http client,
通过查看源代码,没找到上述第一种方式创建的线程池供http相关接口使用
./http/client/http_client_asio.cpp:382:        , m_pool_epoch_timer(crossplat::threadpool::shared_instance().service())
./http/client/http_client_asio.cpp:493:            conn = std::make_shared(crossplat::threadpool::shared_instance().service());
./http/client/http_client_asio.cpp:521:        , m_resolver(crossplat::threadpool::shared_instance().service())
./http/client/http_client_asio.cpp:1861:            : m_duration(timeout.count()), m_state(created), m_timer(crossplat::threadpool::shared_instance().service())
./http/listener/http_server_asio.cpp:520:    auto& service = crossplat::threadpool::shared_instance().service();
./http/listener/http_server_asio.cpp:624:        auto newSocket = new ip::tcp::socket(crossplat::threadpool::shared_instance().service());
./http/listener/http_server_httpsys.cpp:375:    // and with VS2015 PPL tasks run on the threadpool.
./pplx/pplxlinux.cpp:38:    crossplat::threadpool::shared_instance().service().post(boost::bind(proc, param));

cpprest版本:2.10.16

=================================================================

根据①initialize_with_threads接口的说明(Libraries should avoid calling this function to avoid a diamond problem with multiple consumers attempting to customize the pool.),
提供的②schedule(T task)和③service()接口,如果还使用cpprest内的http功能,
推测作者的意图:对于线程池及boost::asio::io_service使用cpprestsdk内构建的对象供整个进程使用。

class threadpool
{
public:
    _ASYNCRTIMP static threadpool& shared_instance();
    _ASYNCRTIMP static std::unique_ptr __cdecl construct(size_t num_threads);

    virtual ~threadpool() = default;

    /// 
    /// Initializes the cpprestsdk threadpool with a custom number of threads
    /// 
    /// 
    /// This function allows an application (in their main function) to initialize the cpprestsdk
    /// threadpool with a custom threadcount. Libraries should avoid calling this function to avoid
    /// a diamond problem with multiple consumers attempting to customize the pool.
    /// 
    /// Thrown if the threadpool has already been initialized
    static void initialize_with_threads(size_t num_threads);

    template
    CASABLANCA_DEPRECATED("Use `.service().post(task)` directly.")
    void schedule(T task)
    {
        service().post(task);
    }

    boost::asio::io_service& service() { return m_service; }

protected:
    threadpool(size_t num_threads) : m_service(static_cast(num_threads)) {}

    boost::asio::io_service m_service;
};

你可能感兴趣的:(总结,c++,cpprest)