home page -> teaching -> parallel and distributed programming -> Lecture extra - Asyncronous calls and coroutines

Lecture extra - Asyncronous calls and coroutines

Coroutines

Coroutine = a code fragment that can get suspended and to be resumed later. A coroutine is a bit similar to a thread, but it explicitly transfer the control to another coroutine.

Simplest examples: Windows fibers. Basic API:

Example: coroutine-fiber-sample.cpp

Coroutine uses:

Generators

Python generator example: coroutine-generator.py

Windows fibers implementation: coroutine-generator.cpp

Async-await mechanism

Simple demo: async-await-short-demo.cs

Downloading web pages examples


  async Task Download(...) {

    await Connect();

    ...

    while(...) {

      await Recv(...);

    }

  }



  for(...) {

    tasks[i] = Download(...)

  }

  Task.WaitAll(tasks);

C++20 coroutines

More about asynchronous functions

Asynchronous function = function that starts some operations that will complete later.

Get the result: polling, blocking, or interrupt (via some callback).

(simple) callbacks - a bit hard to use

Future - allows polling or blocking. Advanced futures allow adding a callback, which is even harder to use.

Higher level handling: some developing on futures; or coroutines.

Composing asynchronous calls:


  Task t1 = Func1();

  Task t2 = t1.ContinueWith(Func2).Unwrap();

Radu-Lucian LUPŞA
2022-12-16