std :: packaged_task <T>(功能模板)是带有调用函数的std :: async(FT)吗?

Trying to work with packaged_task<T>

std::async creates a thread executed asynchronously and process data which we can access into, using the class template std::future<T> and the get() method.

What should i know about how packaged_task<T> works, in difference with std::async ?

And was the thread related to packaged_task<T>, created when we invoked the task(x) function ?

以代码示例为例:

#include <iostream>
#include <thread>
#include <future>
#include <chrono>

using namespace std::chrono;

int main()
{

    int x(0),xr(0);

    std::future<int> fdata = std::async(std::launch::async,[&](int data) mutable throw() ->
                                        int
                                        {data++;
                                        std::this_thread::sleep_for(seconds(2));
                                        return data;}
                                        ,x);

    std::packaged_task<int(int)> task([&](int data) mutable throw() ->
                                        int
                                        {data++;
                                        std::this_thread::sleep_for(seconds(2));
                                        return data;}
                                        );
    std::future<int> xrp = task.get_future();

    task(x);

    xr=fdata.get();

    std::cout<<xr<<std::endl;
    std::cout<<xrp.get()<<std::endl;

    return 0;
}
评论
  • 1种矜持
    1种矜持 回复

    std::async(ploicy, callable, args...)
    

    launches a new thread (if the resources are available) if the policy is std::async::launch.

    如果未确定该策略,则可能无法启动。

    If the policy is std::async::deferred, won't launch.

    while std::packaged_task wraps your callable so that it can be invoked asynchronously using a new thread like

    auto t1 = std::thread(std::move(taskObj), args...);
    ....
    t1.join();
    

    但是,如果像在示例中一样使用它,它将不会启动新线程。它本身不会启动新线程,但可以用来启动新线程。