c++:使用 packaged_task 构建异步

标签 c++ multithreading templates c++11 packaged-task

我正在尝试使用 packaged_task 实现异步。我正在通过一个模板化函数 bsync 来尝试这个。 bsync 接受 2 个参数:一个函数 f 和一个参数包 args,并返回一个 future fut。 future 是 f(args...) 返回的类型。即 - 返回是 future 的

我想我快完成了,但是我遇到了类型转换错误。任何帮助将不胜感激:

#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>
#include <functional>
#include <type_traits>
using namespace std;


//Implement bsync as a templated function
//Template parameters are (i) Fn (the function to run), (ii) Args, a parameter pack of arguments to feed the function
//The function returns a future<Ret>, where Ret is the return-type of Fn(Args)
template<class Fn,class...Args>
auto bsync(Fn f, Args&&...args)->future<result_of<decltype(f)&(Args&&...)>>{

    //Determine return-type
    typedef result_of<decltype(f)&(Args&&...)>::type A;

    //Initialize a packaged_task
    packaged_task <A(Args&&...)>tsk(f);

    //Initialize a future
    future<A> fut = tsk.get_future();

    //Run the packaged task in a separate thread
    thread th(move(tsk),(args)...);

    //Join the thread
    th.join();

    return fut;
}

int plus_one(int x){
    cout << "Adding 1 to " << x << endl;
    return x++;
}

int main(){
    auto x = bsync(plus_one, 1);

    cout << "Press any key to continue:" << endl;
    cin.ignore();
    return 0;
}

最佳答案

您的尾随返回类型不正确。你有:

future<result_of<decltype(f)&(Args&&...)>>

那是一个future与类型 result_of<...> .您需要实际评估 result_of生成实际结果类型的元函数。即:

future<typename result_of<Fn(Args&&...)>::type>
       ^^^^^^^^^                        ^^^^^^

一旦你解决了这个问题,你就错过了一个 typename在你的typedef对于 A .

关于c++:使用 packaged_task 构建异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034461/

相关文章:

c++ - 显式模板实例化 : MSVC vs. GCC

c++ - 重载通用句柄类的赋值运算符

c++ - std::function 无法区分重载函数

c++ - 如果静态成员未初始化并且成员类型是类本身怎么办?

c++ - 为矩阵迭代器在+ =之间集成一个条件(可能对数学有挑战)

c++ - 为什么下面的程序会报错?

multithreading - Delphi中如何将异常从一个线程传递到另一个(调用者的)线程?

c++ - 如何更快地读取多个文件?

java - 如何并行而不是顺序执行多个查询?

C++ 模板偏特化