namespace cpp {}

C++ lernen, kennen, anwenden

Benutzer-Werkzeuge

Webseiten-Werkzeuge


kennen:coroutine

Unterschiede

Hier werden die Unterschiede zwischen zwei Versionen angezeigt.


kennen:coroutine [2020-07-13 15:43] (aktuell) – angelegt - Externe Bearbeitung 127.0.0.1
Zeile 1: Zeile 1:
 +====== Coroutinen ======
  
 +Coroutinen enthalten eines der Schlüsselwörter [[.:keywords#co_yield]], [[.:keywords#co_return]] oder [[.:keywords#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 =====
 +
 +<code cpp 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';
 +}
 +</code>
 +
 +Die Ausgabe zeigt, wie die Coroutinen interagieren:
 +
 +<file>
 + 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
 +</file>

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki