有人可以解释我在这里做错了什么:
#include <future>
#include <iostream>
int main() {
std::future<int> result( std::async([](int m) { return m+1;}, 2));
std::cout << "In main" << std::endl;
std::cout << result.get();
}
使用 GCC 4.8 或 4.9 时,出现段错误。
:
./a.out:
In main
Segmentation fault: 11
: /opt/local/bin/g++-mp-4.8 -v
Using built-in specs.
COLLECT_GCC=/opt/local/bin/g++-mp-4.8
COLLECT_LTO_WRAPPER=/opt/local/libexec/gcc/x86_64-apple-darwin12/4.8.1/lto-wrapper
Target: x86_64-apple-darwin12
Configured with: ../gcc-4.8.1/configure --prefix=/opt/local --build=x86_64-apple-darwin12 --enable-languages=c,c++,objc,obj-c++,lto,fortran,java --libdir=/opt/local/lib/gcc48 --includedir=/opt/local/include/gcc48 --infodir=/opt/local/share/info --mandir=/opt/local/share/man --datarootdir=/opt/local/share/gcc-4.8 --with-local-prefix=/opt/local --with-system-zlib --disable-nls --program-suffix=-mp-4.8 --with-gxx-include-dir=/opt/local/include/gcc48/c++/ --with-gmp=/opt/local --with-mpfr=/opt/local --with-mpc=/opt/local --with-ppl=/opt/local --with-cloog=/opt/local --enable-cloog-backend=isl --disable-cloog-version-check --enable-stage1-checking --disable-multilib --enable-lto --enable-libstdcxx-time --with-as=/opt/local/bin/as --with-ld=/opt/local/bin/ld --with-ar=/opt/local/bin/ar --with-bugurl=https://trac.macports.org/newticket --with-pkgversion='MacPorts gcc48 4.8.1_0'
Thread model: posix
gcc version 4.8.1 (MacPorts gcc48 4.8.1_0)
编辑:有些人指出了另一个答案,上面写着与 pthread 的链接。这并不能解决问题:
: /opt/local/bin/g++-mp-4.8 -std=c++11 -lpthread thread5.cc
: ./a.out
In main
Segmentation fault: 11
最佳答案
我已经用 clang 3.2(apple llvm 4.2) 测试了代码,它运行得很好。它返回
In main
3
编辑:
其他人也用 gcc 4.8.1 测试过,它可以工作。最可能的问题是您正在链接到默认的 pthread 库,而不是来自 macports 的 gcc 4.8.1 附带的库
关于multithreading - C++11 异步段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17307388/