这是我的问题的准确再现:
#include <vector>
#include <future>
using namespace std;
typedef unsigned Counter;
typedef vector<Counter> Counters;
Counters computer(int n)
{
Counters result(n, 0);
return result;
}
int main(void)
{
int num_workers = 1;
int n = 10;
// set workers to work
vector<future<Counters>> workers(num_workers);
for (auto& worker : workers) worker = async(computer, n);
// collect results
Counters result (n,0);
for (auto& worker : workers)
{
Counters partial = worker.get();
for (size_t i = 0; i != partial.size(); i++) result[i] += partial[i];
}
return 0;
}
我必须在这里做一些明显错误的事情。令人讨厌的部分是,代码在Win7下在MSVC2013和MinGW上编译并运行良好,但是在使用g ++ 4.8的Ubuntu上产生了这个神秘的崩溃:
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)
gdb增加了这个重要的智慧:
Program received signal SIGABRT, Aborted.
0x00132416 in __kernel_vsyscall ()
#0 0x00132416 in __kernel_vsyscall ()
#1 0x00272e0f in raise () from /lib/i386-linux-gnu/libc.so.6
#2 0x00276455 in abort () from /lib/i386-linux-gnu/libc.so.6
#3 0x0017fc65 in __gnu_cxx::__verbose_terminate_handler() ()
from /usr/lib/i386-linux-gnu/libstdc++.so.6
#4 0x0017d943 in ?? () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#5 0x0017d9bd in std::terminate() ()
from /usr/lib/i386-linux-gnu/libstdc++.so.6
#6 0x0017dc81 in __cxa_throw () from /usr/lib/i386-linux-gnu/libstdc++.so.6
#7 0x001d7ebd in std::__throw_system_error(int) ()
from /usr/lib/i386-linux-gnu/libstdc++.so.6
#8 0x0804a1cd in _ZSt9call_onceIMNSt13__future_base11_State_baseEFvRSt8functionIFSt10unique_ptrINS0_12_Result_baseENS4_8_DeleterEEvEERbEJKPS1_St17reference_wrapperIS8_ESF_IbEEEvRSt9once_flagOT_DpOT0_ ()
#9 0x08049beb in std::__future_base::_State_base::_M_set_result(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>, bool) ()
#10 0x0804f274 in std::__future_base::_Deferred_state<std::_Bind_simple<std::vector<unsigned int, std::allocator<unsigned int> > (*(int))(int)>, std::vector<unsigned int, std::allocator<unsigned int> > >::_M_run_deferred() ()
#11 0x08049afd in std::__future_base::_State_base::wait() ()
#12 0x0804b20d in std::__basic_future<std::vector<unsigned int, std::allocator<unsigned int> > >::_M_get_result() const ()
#13 0x0804a7c6 in std::future<std::vector<unsigned int, std::allocator<unsigned int> > >::get() ()
#14 0x0804960c in main ()
错误是由第28行的worker.get();
引起的。
我只在VM中使用Ubuntu来检查可移植性,而且我并不熟悉本地调试环境,所以我没有深入研究它。
问题是:到底发生了什么事?
答案 0 :(得分:2)
好的,答案是:用-pthread
编译,或者......