Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::async不';不能并行化任务_C++_Gcc_C++11 - Fatal编程技术网

C++ std::async不';不能并行化任务

C++ std::async不';不能并行化任务,c++,gcc,c++11,C++,Gcc,C++11,在此代码段中使用C++11 std::async: int foo() { ::sleep(2); return 123; } int main() { future<int> r1(async(foo)); int r2 = foo(); cout << r1.get() + r2 << endl; return 0; } intfoo() { ::睡眠(2); 返回123; } int main() {

在此代码段中使用C++11 std::async:

int foo()
{
    ::sleep(2);
    return 123;
}

int main()
{
    future<int> r1(async(foo));
    int r2 = foo();
    cout << r1.get() + r2 << endl;
    return 0;
}
intfoo()
{
::睡眠(2);
返回123;
}
int main()
{
未来r1(异步(foo));
int r2=foo();
cout您可能需要添加一组
std::launch::async

std::async(std::launch::async, foo);

std::future受到批评,例如在CppCon演示文稿中,它的速度太慢。您可以通过使用完全避免std::async和std:future。您可以异步运行任意数量的函数,并以元组形式获取结果。此外,还可以正常捕获异常

以下是一个例子:

#包括
#包括“Lazy.h”
模板
T foo(T x){
std::this_线程::sleep_for(std::chrono::毫秒(1000));
返回x+10.5;
}
int main(){
int输入=54;
试一试{
自动[i,d,c]=惰性::运行并行(
[&](){return foo(int(input));},
[&](){return foo(double(input));},
[&](){returnfoo(char(input));};

std::cout注意到,尽管g++支持
async
的语法,但它的实现还相当不成熟(与MSVC相比)。哦,我明白了……所以答案是,它现在是一个模拟实现?@Martin:我不会说是模拟,但它非常原始。例如,如果您将
async
指定为策略,则运行时可以启动一个新线程或从池中获取它(如果所述池为空,则可能会延迟其启动).在gcc中,它总是启动一个新线程,所以当你达到1000个线程时…你就有麻烦了。我总是喜欢简单的解决方案。工作起来很有魅力。