I am trying to build a work queue of functions that must be executed by a single thread and can be powered by many threads. For this, I planned to use boost :: packaged_task and boost :: unique_future. The idea would be:
Value Foo = queue.add (myFunc) .get ();
which blocks until the function is executed. So queue.add (...) takes a boost :: function and returns boost :: unique_future. Then inside he creates boost :: packaged_task, using boost :: function for his constructor.
The problem I am facing is that boost :: function <...> will not be the same every time. In particular, the return value for it will change (functions, however, will never take any parameters). So I should have an add function that looks something like this:
template <typename ResultType> boost::unique_future<ResultType> add(boost::function<ResultType ()> f) { boost::packaged_task<boost::function<ResultType ()> > task(f); queue.push_back(task); return task.get_future(); }
Well, that doesn't seem too bad, but then I ran into the problem of defining a โqueueโ. I think I have no choice but to use boost :: any, since the types will not be constant:
std::list<boost::any> queue; // note: I'm not concerned with thread-safety yet
But then I encounter a problem when I try to implement my executeSingle (takes only one element from the queue to execute):
void executeSingle() { boost::any value = queue.back(); boost::packaged_task<?> task = boost::packaged_task<?>(boost::move(value)); // actually execute task task(); queue.pop_back(); }
"?" that i'm not sure. I cannot call executeSingle with a template, as it called from a separate thread. I tried using boost :: any, but getting an error:
conversion from 'boost::any' to non-scalar type boost::detail::thread_move_t<boost:thread>' requested.
The funny thing is that at the moment I donโt care about the packaged_task return type, I just want to execute it, but I can figure out the details of the template.
Any understanding would be greatly appreciated!