相关疑难解决方法(0)

使用boost asio的线程池

我正在尝试使用boost :: asio创建一个有限的线程池类.但是我被困在某一点可以帮助我.

唯一的问题是我应该减少反击的地方?

代码无法按预期工作.

问题是我不知道我的线程何时完成执行以及我将如何知道它已经返回池中

#include <boost/asio.hpp>
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <stack>

using namespace std;
using namespace boost;

class ThreadPool
{
    static int count;
    int NoOfThread;
    thread_group grp;
    mutex mutex_;
    asio::io_service io_service;
    int counter;
    stack<thread*> thStk ;

public:
    ThreadPool(int num)
    {   
        NoOfThread = num;
        counter = 0;
        mutex::scoped_lock lock(mutex_);

        if(count == 0)
            count++;
        else
            return;

        for(int i=0 ; i<num ; ++i)
        {
            thStk.push(grp.create_thread(boost::bind(&asio::io_service::run, &io_service)));
        }
    }
    ~ThreadPool()
    {
        io_service.stop();
        grp.join_all();
    }

    thread* getThread()
    { …
Run Code Online (Sandbox Code Playgroud)

c++ boost-asio threadpool

20
推荐指数
1
解决办法
2万
查看次数

如何将通用的packaged_tasks存储在容器中?

我正试图采用一种"任务"的风格std::async并将其存放在容器中.我不得不跳过篮球来实现它,但我认为必须有更好的方法.

std::vector<std::function<void()>> mTasks;

template<class F, class... Args>
std::future<typename std::result_of<typename std::decay<F>::type(typename std::decay<Args>::type...)>::type>
push(F&& f, Args&&... args)
{
    auto func = std::make_shared<std::packaged_task<typename std::result_of<typename std::decay<F>::type(typename std::decay<Args>::type...)>::type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
    auto future = func->get_future();

    // for some reason I get a compilation error in clang if I get rid of the `=, ` in this capture:
    mTasks.push_back([=, func = std::move(func)]{ (*func)(); });

    return future;
}
Run Code Online (Sandbox Code Playgroud)

所以我正在使用bind- > packaged_task- > shared_ptr- > lambda- > function.我怎样才能更好/更优化?如果有一个std::function可以采取不可复制但可移动的任务,那肯定会更容易.我可以std :: forward …

c++ multithreading c++11 c++14

6
推荐指数
1
解决办法
1426
查看次数

标签 统计

c++ ×2

boost-asio ×1

c++11 ×1

c++14 ×1

multithreading ×1

threadpool ×1