vendredi 25 août 2017

std::future error when passed (Templates)

I'm doing a thread pool implementation and I'm trying to make it to support futures. Unfortunately the code seems to have some problems. When I pass a callable that returns void there is a std::future_error: No associated state at runtime.

If i try to pass a function that returns int there is an error which says

error: could not convert ‘std::packaged_task<_Res(_ArgTypes ...)>::get_future() with _Res = void; _ArgTypes = {}’ from ‘std::future’ to ‘std::future’ return queue[curElem].get_future();

I think the problem is in the method that adds the tasks, who looks like

template<typename F, typename ... ARGS>
auto ThreadPool::add_task(F && func, ARGS && ... args) ->std::future<decltype(func(args...))>
{
    if (!stop)
    {
        auto pck = std::packaged_task< decltype(func(args...)) () >(
            std::bind(std::forward<F>(func), std::forward<ARGS>(args)...));

        mutex.lock();
        queue.emplace_back(std::move(pck));
        auto curElem = queue.size()-1;
        mutex.unlock();
        wait_var.notify_one();

        return queue[curElem].get_future();
    }
    else
    {
        return std::future<decltype(func(args...))>();
    }
}

At the moment I'm experimenting with a different kind of queues. This particular implementation is with std::vector for a queue. The other is with std::deque. std::vector<std::packaged_task<void()>> queue;

Aucun commentaire:

Enregistrer un commentaire