C++ C++;当打包的_任务包装在线程中时,未指定的未来_errc值,代码4

C++ C++;当打包的_任务包装在线程中时,未指定的未来_errc值,代码4,c++,multithreading,future,packaged-task,C++,Multithreading,Future,Packaged Task,正如下面的代码所示,我试图通过传递打包的任务来实现自己的线程类。然后我等待这个打包的任务的未来。我希望这段代码等待4秒,然后我可以从未来获取0xCDCD #include <iostream> #include <future> using namespace std; class mythread { public: thread internal_thread; template <typename _Fn> mythread(_Fn

正如下面的代码所示,我试图通过传递打包的任务来实现自己的线程类。然后我等待这个打包的任务的未来。我希望这段代码等待4秒,然后我可以从未来获取0xCDCD

#include <iostream>
#include <future>

using namespace std;

class mythread {
public:
    thread internal_thread;
    template <typename _Fn> mythread(_Fn f) {
        internal_thread = thread([&f] {
            try {
                f();
            }
            catch (std::exception& e) {
                this_thread::sleep_for(chrono::seconds(4));
                std::cout << e.what() << std::endl;
            }
        });
    }
};

int work() {
    this_thread::sleep_for(chrono::milliseconds(2000));
    return 0xcdcdcdcd;
}

int main() {
    packaged_task<int()> task(work);
    future<int> ftr = task.get_future();
    mythread thrd(move(task));

    ftr.wait();
    cout << "Got it!!" << endl;
    try {
        cout << ftr.get() << endl;
    }
    catch (future_error &e) {
        std::cout << "outer " << e.code() << e.what() << std::endl;
    }
    cout << "Ended" << endl;
    getchar();
}
环境是OS X 10.11.1

$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
编译命令是

g++ --std=c++11 main.cpp && ./a.out
我不确定它是否会在其他平台上复制

提前谢谢

编辑 已解决:这是因为
mythread
的构造函数现在控制移入的
f
的生存时间,线程使用其引用。但是构造函数在创建线程后立即返回,从而销毁了所有局部变量,包括
f
,而线程仍然保存着被销毁的局部变量

更正后的代码为

class mythread {
public:
    thread internal_thread;
    template <typename _Fn> mythread(_Fn f) {
        internal_thread = thread([] (_Fn f) {
            try {
                f();
            }
            catch (std::exception& e) {
                this_thread::sleep_for(chrono::seconds(4));
                std::cout << e.what() << std::endl;
            }
        }, move(f));
    }
};
类读取{
公众:
内螺纹;
模板读取(_fnf){
内螺纹=螺纹([])(\u Fn f){
试一试{
f();
}
捕获(标准::异常&e){
这个线程:睡眠(时间:秒(4));

std::我想这是因为当你调用
mythread thrd(move(task));
task
的共享状态被移走,
task
不再有任何共享状态,
ftr
-与
task
共享相同的状态-不再有任何共享状态,因此没有什么东西可以等待。call
ftr.valid()
移动之后,看看你得到了什么。我想这是因为当你调用mythread thrd(移动(任务))时
任务
中移除共享状态,
任务
不再具有任何共享状态,
ftr
-与
任务
共享相同状态-不再具有任何共享状态,因此无需等待。移动后调用
ftr.valid()
,查看您得到了什么。
class mythread {
public:
    thread internal_thread;
    template <typename _Fn> mythread(_Fn f) {
        internal_thread = thread([] (_Fn f) {
            try {
                f();
            }
            catch (std::exception& e) {
                this_thread::sleep_for(chrono::seconds(4));
                std::cout << e.what() << std::endl;
            }
        }, move(f));
    }
};