mercredi 28 juillet 2021

when to prefer lambda over packaged task with std::async? [duplicate]

I am bit confused as when do i need to pass packaged_task to std::async. Do i really need std::packaged_task when i can directly pass the function with arguments? Is there something which is possible only with packaged task and not with normal function approach?

Approach 1: std::async with lambda function

std::future<int> result= std::async(std::launch::async, [](int m, int n) { return m + n;} , 2, 4));

Approach 2: std::async with packaged_task,

        auto f = [](int m, int n) { return m + n;};
        std::packaged_task<int(int,int)> task(f);
        std::future<int> result = task.get_future();
     
        std::async(std::launch::async, std::move(task), 2, 4);
        int ans = result.get();
        

I have checked for answers but none of them gives me a proper use case. It looks like coder can just use any of these approaches BUT when does one scores over other?

Aucun commentaire:

Enregistrer un commentaire