为什么我的任务继续无法执行?

时间:2019-05-17 10:43:36

标签: c++ visual-studio task ppl

我正在学习在C ++中使用任务。

在这里我不明白为什么我的任务继续执行从未执行:

#include <iostream>
#include <ppltasks.h>
using namespace concurrency;

const concurrency::task<void> f1()
{
    std::cout << "Inside f1() \n";
    concurrency::task<void> rv;
    return rv;
}

const concurrency::task<void> f2()
{
    std::cout << "Inside f2() \n";
    concurrency::task<void> rv;
    return rv;
}

const concurrency::task<void> f3()
{
    std::cout << "Inside f3() \n";
    concurrency::task<void> rv;
    return rv;
}

int main()
{
    std::cout << "The BEGIN !\n"; 

    auto myTask = create_task(f1).then([&]() {  std::cout << "Affter         f1() \n"; });
    auto mytask2 = create_task(f2) && create_task(f3).then([=]() {      std::cout << "Affter f3() \n"; });

    myTask.then([&]() { std::cout << "Affter f1() \n"; });

    for (int i = 0; i < 10; i++)
    {
        std::cout << "The END !\n\n";
    }
}

以下是程序产生的内容:

The BEGIN !
Inside f1()
Inside f3()
Inside f2()
The END !

The END !

The END !

The END !

The END !

The END !

The END !

The END !

The END !

The END !

编辑:

更好地理解任务后,我将程序更改为:

#include "pch.h"
#include <iostream>
#include <ppltasks.h>
using namespace concurrency;

task<void> f1()
{
    return create_task([] {std::cout << "Inside f1() \n"; }).then([] {std::cout << "Continuation of f1() \n"; });
}

task<void> f2()
{
    return create_task([] {std::cout << "Inside f2() \n"; }).then([] {std::cout << "Continuation of f2() \n"; });
}


task<void> f3()
{
    return create_task([] {std::cout << "Inside f3() \n"; }).then([] {std::cout << "Continuation of f3() \n"; });
}


int main()
{
    std::cout << "The BEGIN !\n"; 

    auto myTask1 = f1();
    auto myTask2 = f2();
    auto myTask3 = f3();

    //  use get() to wait for all 3 tasks and their continuations to be done
    (myTask1 && myTask2 && myTask3).get();

    std::cout << "The END !\n";
}

现在似乎可以了,并给出以下结果:

The BEGIN !
Inside f1()
Inside f2()
Inside f3()
Continuation of f2()
Continuation of f3()
Continuation of f1()
The END !

因此,如果我现在对它的理解很好,那么我就不能像在第一个代码版本中那样尝试将连续性单独添加到任务中?

EDIT2:

好的,我错了,我们可以很好地分开添加一个延续,像这样:

int main()
{
    std::cout << "The BEGIN !\n"; 

    auto myTask1 = f1();
    auto myTask2 = f2();
    auto myTask3 = f3();

    auto completeTask = (myTask1 && myTask2 && myTask3).then([] {std::cout << "All tasks done !!! \n"; });

    //  use get() to wait for all 3 tasks and their continuations to be done
    completeTask.get();

    std::cout << "The END !\n";
}

这将产生该结果:

The BEGIN !
Inside f1()
Inside f2()
Inside f3()
Continuation of f1()
Continuation of f3()
Continuation of f2()
All tasks done !!!
The END !

现在我终于有了我想要的东西,谢谢大家。

0 个答案:

没有答案