When I use std::function, I got a mistake of receiving the signal SIGABRT. Why?

Viewed 44

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 ....

1 Answers

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

Related