-1

I want to use submit to construct a function, which can be used in other threads. And In order not to be blocked, submit will return std::future, which can let me get the return value in the proper time. My code is below:

std::vector<std::function<void()>> fuctions(0);
std::vector<std::future<int>> futures(0);

template <typename Function, typename ...Args>
std::future<typename std::result_of_t<Function(Args...)>> submit(Function f, Args... args) {
  using result_type = typename std::result_of_t<Function(Args...)>;
  std::function<result_type()> func = std::bind(std::forward<Function>(f), std::forward<Args>(args)...);
  auto task_ptr = std::make_shared<std::packaged_task<result_type()>>(func);
  std::function<void()> wrapper_fuc = [task_ptr]() {
    (*task_ptr)();
  };
  fuctions.push_back(wrapper_fuc);
  return task_ptr->get_future();
} 

int add(int a, int b) {
  return a + b;
}

int main() {

  futures.push_back(std::move(submit(add, 1, 2)));
  futures.push_back(std::move(submit(add, 2, 2)));
  futures.push_back(std::move(submit(add, 3, 2)));
  futures.push_back(std::move(submit(add, 4, 2)));
  futures.push_back(std::move(submit(add, 5, 2)));
  futures.push_back(std::move(submit(add, 6, 2)));
  futures.push_back(std::move(submit(add, 7, 2)));
  futures.push_back(std::move(submit(add, 8, 2)));

  std::cout << "do functions" << std::endl;
  for (int i = 0; i < fuctions.size(); ++i) {
    fuctions[i]();
  }
  std::cout << "functions done" << std::endl;
  
  for (int i = 0; i < futures.size(); ++i) {
    std::cout << "get result : " << futures[i].get() << std::endl;
  }
}

this line fuctions[i]() raises the exception, detailed infomation is below

terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1

Program received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
50      ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.

I don't know why ....

273K
  • 29,503
  • 10
  • 41
  • 64
  • Your function already returns temporary, your `std::move()` call is redundant – Slava Sep 12 '22 at 01:24
  • You should not `std::move` returned values (already rvalues). – 273K Sep 12 '22 at 01:54
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Sep 12 '22 at 02:52
  • Probably `-pthread` is needed when compiling, more info [here](https://stackoverflow.com/questions/41790363/c-core-dump-with-packaged-task), working version with pthread you have under [this link](https://godbolt.org/z/KMGjfWPMo), without pthread, `system_error` is thrown as in your case. – rafix07 Sep 12 '22 at 06:23
  • With @rafix07 help, -pthread is exactly what i need, thank you guys – peng zhang Sep 12 '22 at 14:05

1 Answers1

0

With @rafix07 help, -pthread is exactly what I need, this link indicated the difference between -lpthread and -pthread.