相关疑难解决方法(0)

threadpool c ++实现问题

在这里这里,我们可以看到类似的线程池实现.

我的问题是关于将任务添加到线程池的功能,这些是分别在上面的项目中添加排队.

因为这些看起来非常相似我在这里张贴了一块(来自第二个项目)

auto ThreadPool::enqueue(F&& f, Args&&... args) 
-> std::future<typename std::result_of<F(Args...)>::type>
{
    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared< std::packaged_task<return_type()> >(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

    // don't allow enqueueing after stopping the pool
        if(stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task](){ (*task)(); });
    }
    condition.notify_one();
    return res;
}
Run Code Online (Sandbox Code Playgroud)

容器任务声明为:

std::queue< std::function<void()> > tasks;
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

  1. 为什么使用附加包装器std :: function声明的任务围绕任务变量?为什么任务的队列没有被声明为std :: packaged_task的容器,它也是一个可调用的对象?我认为任务队列应包含没有参数且没有返回类型的"通用"可调用对象.所以通过绑定实现删除参数,额外的包装器std :: function有助于删除返回类型,是正确还是不正确?还有关于shared_ptr的使用 - …

c++ concurrency multithreading threadpool

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

标签 统计

c++ ×1

concurrency ×1

multithreading ×1

threadpool ×1