My attempt to write a thread pool implementation has stalled out because of issues with the function template responsible for submitting tasks to the pool itself.
I've reduced the code down to its most basic components: creating a std::promise
object, assigning to it, and returning its std::future
object, and I'm still getting the error.
#include<future>
#include<iostream>
template<typename Func, typename Ret>
void set(std::promise<Ret> & promise, Func && func) {
promise.set_value(func());
}
template<typename Func>
void set(std::promise<void> & promise, Func && func) {
func();
promise.set_value();
}
template<typename Func, typename ... Args>
auto execute(Func && func, Args && ... args) ->
std::future<decltype(func(args...))> {
using Ret = decltype(func(args...));
std::promise<Ret> promise;
set(promise, [&]{return func(std::forward<Args>(args)...);});
return promise.get_future();
}
void reverse(std::string & string) {
for(size_t i = 0; i < string.size() / 2; i++)
std::swap(string[i], string[string.size() - 1 - i]);
}
int main() {
try{
std::string string = "Hello World!";
auto future2 = execute(reverse, string);
future2.get();
std::cout << string << std::endl;
} catch(std::system_error const& e) {
std::cerr << e.what() << std::endl;
std::cerr << e.code() << std::endl;
}
}
Console Output:
Unknown Error: -1
generic: -1
From debugging, the error appears to occur exactly at the moment I call set_value
on the promise
object; what am I doing wrong?