namespace cpp {}

C++ lernen, kennen, anwenden

Benutzer-Werkzeuge

Webseiten-Werkzeuge


kennen:coroutine

Coroutinen

Coroutinen enthalten eines der Schlüsselwörter co_yield, co_return oder co_await.

Funktionen berechnen einen Wert und geben ihn zurück. Coroutinen können einen Wert liefern (yield), ihre Arbeit unterbrechen (suspend) und weiterarbeiten (resume), wo sie pausiert haben.

Beispiel

coro_pythagorean.cpp
#include <experimental/generator> // MS VC++ /await /std=c++latest
#include <iostream>
#include <numeric>
#include <tuple>
 
using Triple = std::tuple<int, int, int>;
using namespace std::experimental;
 
generator<Triple> pythagorean_triples(int limit)
{
    for (auto z = 1; z < limit; ++z)
        for (auto y = 1; y < z; ++y)
            for (auto x = 1; x < y; ++x)
                if (x * x + y * y == z * z)
                {
                    std::cout << '\t' << x << ' ' << y << ' ' << z << '\n';
                    co_yield {x, y, z};
                }
}
 
generator<Triple> irreducible_pythagorean_triples(int limit)
{
    for (auto [x, y, z] : pythagorean_triples(limit))
        if (std::gcd(x, z) == 1 && std::gcd(y, z) == 1)
            co_yield {x, y, z};
}
 
int main()
{
    std::cout << "\tpythagorean triple\nirreducible\n";
 
    for (auto [x, y, z] : irreducible_pythagorean_triples(30))
        std::cout << x << ' ' << y << ' ' << z << '\n';
}

Die Ausgabe zeigt, wie die Coroutinen interagieren:

	pythagorean triple
irreducible
	3 4 5
3 4 5
	6 8 10
	5 12 13
5 12 13
	9 12 15
	8 15 17
8 15 17
	12 16 20
	15 20 25
	7 24 25
7 24 25
	10 24 26
	20 21 29
20 21 29
kennen/coroutine.txt · Zuletzt geändert: 2020-07-13 15:43 von 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki