Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以分离内部std::future线程吗?_C++_C++11 - Fatal编程技术网

C++ 我可以分离内部std::future线程吗?

C++ 我可以分离内部std::future线程吗?,c++,c++11,C++,C++11,考虑以下代码: template <typename func_t, typename ... Args> auto waiter (func_t func, const Args &... args) -> decltype(func(args...)) { const static std::chrono::milliseconds max_time(10); auto task = std::packaged_task<decltype(func(a

考虑以下代码:

template <typename func_t, typename ... Args>
auto waiter (func_t func, const Args &... args) -> decltype(func(args...)) {
  const static std::chrono::milliseconds max_time(10);
  auto task = std::packaged_task<decltype(func(args...))()>(std::bind(func, args...));
  auto handle = task.get_future();
  std::thread th(std::move(task)); // here
  if (handle.wait_for(max_time) == std::future_status::timeout) {
    th.detach(); // and here
    throw std::runtime_error("timeout");
  } else { // and here
    th.detach();
    return handle.get();
  }
}
这里的问题是在抛出异常后,
std::thread
th
仍在使用终止引用运行。第二次尝试:

template <typename func_t, typename ... Args>
auto waiter (func_t func, const Args &... args) ->     decltype(func(args...)) {
  const static std::chrono::milliseconds max_time(10);
  auto handle = std::async(std::launch::async, func, args ...);
  if (handle.wait_for(max_time) == std::future_status::timeout) {
    throw std::runtime_error("timeout");
  } else {
    return handle.get();
  }
}
模板
自动侍者(func_t func,const Args&…Args)->decltype(func(Args…){
常量静态标准::计时::毫秒最大时间(10);
自动句柄=std::async(std::launch::async、func、args…);
if(handle.wait_for(max_time)=std::future_status::timeout){
抛出std::运行时_错误(“超时”);
}否则{
返回句柄.get();
}
}
这里的问题是(据我所知),
std::async::~async()
在其内部线程上调用某种
std::thread::join()
,而主线程仍在等待
std::async

愚蠢的一个。

您可以像第一次尝试那样分离线程,但是,正如您所说,线程将继续分离运行,直到它自己完成为止

第二次尝试的问题是,由
std::async
返回的
std::future
与它的析构函数一样特殊(与常规的
std::future
的析构函数不同)

<>我恐怕在C++中不可能安全地终止一个线程而不杀死所有线程。该问题源于执行期间在任意点安全展开堆栈的困难。如果让我们说,退绕应该发生在一个不合适的地方,如ctor或dtor,它将打破对象存储持续时间的规则

有关更多详细信息,请参阅

template <typename func_t, typename ... Args>
auto waiter (func_t func, const Args &... args) ->     decltype(func(args...)) {
  const static std::chrono::milliseconds max_time(10);
  auto handle = std::async(std::launch::async, func, args ...);
  if (handle.wait_for(max_time) == std::future_status::timeout) {
    throw std::runtime_error("timeout");
  } else {
    return handle.get();
  }
}