c – 当未来离开范围时,线程在哪里?

前端之家收集整理的这篇文章主要介绍了c – 当未来离开范围时,线程在哪里?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用线程我知道当线程变量离开作用域时会调用terminate():
size_t fibrec(size_t n) {
  return n<2 ? 1 : fibrec(n-2)+fibrec(n-1);
}

int main() {
    std::thread th{ fibrec,35 };
    // no join here
} // ~th will call terminate().

析构函数在离开作用域时会调用terminate().

但期货怎么样?他们运行的线程在哪里?它是分离的吗?它是如何结束的?

#include <iostream>
#include <future> // async
using namespace std;

size_t fibrec(size_t n) {
    return n<2 ? 1 : fibrec(n-2)+fibrec(n-1);
}

struct Fibrec {
    size_t operator()(size_t n) { return fibrec(n); }
    const size_t name_;
    Fibrec(size_t name) : name_(name) {}
    ~Fibrec() { cerr << "~"<<name_<< endl; }
};

void execit() {
    auto f1 = async( Fibrec{33},33 );
    auto f2 = async( Fibrec{34},34 );
    // no fx.get() here !!!
}; // ~f1,~f2,but no terminate()! Where do the threads go?

int main() {
    auto f0 = async( Fibrec{35},35 );
    execit();
    cerr << "fib(35)= " << f0.get() << endl;
}

当execit()离开时,期货f1和f2被销毁.但他们的线程应该还在运行?当然,称为Fibrec的析构函数.但线程在哪里?程序没有崩溃,所以我想,加入了吗?或者可能超脱?或者他们被停止或取消?我相信在C 11中并不是一件容易的事吗?

解决方法

未来是异步操作的结果,它本身不是一个线程. async函数生成一个新线程来执行计算,完成后,结果将写入future对象.

根据实施的策略,您将需要在将来调用.get()或.wait()来获取结果.调用它将在调用它的线程上完成工作

If policy is std::launch::async then runs INVOKE(fff,xyz…) on its
own thread. The returned std::future will become ready when this
thread is complete
,and will hold either the return value or exception
thrown by the function invocation. The destructor of the last future
object associated with the asynchronous state of the returned
std::future shall block until the future is ready.

If policy is std::launch::deferred then fff and xyz… are stored in the returned std::future as a deferred function call. The first call to the wait() or get() member functions on a future that shares the same associated state will execute INVOKE(fff,xyz…) synchronously on the thread that called wait() or get().

原文链接:https://www.f2er.com/c/115879.html

猜你在找的C&C++相关文章