正如下面的代码所示,我试图通过传入一个 packaged_task 来实现我自己的线程类。然后我等待这个 packaged_task 的未来。我希望这段代码等待 4 秒,然后我可以从未来得到 0xcdcdcdcd。
#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();
}
但是等待似乎立即终止了这个任务。通过编译执行这段代码,它会立即打印出来
Got it!!
outer future:4unspecified future_errc value
Ended
环境是 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
now的构造函数控制了搬入的生命周期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));
}
};
其中的控制f
被进一步移动到线程中。