by Joker_vD · 6y ago · 0 comments
async func foo(x int) task[int] { return await(2 * x); }
// No "async" only because cpu_bound_future_factory() returns a task
func bar(y int) task[int] { return cpu_bound_future_factory(async func() task[int] { return await(y - 5); }); }
async func baz(a,b int) task[int] { return await(await foo(a) + await bar(b)); }
is not fun, especially when you have to await the result of the arithmetic operators, and write all those now-redundant async and await, so let's also drop "async" and make "await" implicit--although we'll need something for non-awaiting. Let's call it "nowait". Now we can write code like this: func foo(x int) task[int] { return 2 * x; }
func bar(y int) task[int] { return nowait cpu_bound_future_factory(func() task[int] { return y - 5; }); }
func baz(a, b int) task[int] { return foo(a) + bar(b); }
A-a-and we're back to multithreading, basically. So yeah, looks like cheap context switches is the solution.My idea is to make the continuation explicit and CPS transform all and only the functions that have a continuation as parameter (and any generic function with a type that is a continuation or contains a continuation). Fall back to dynamic stacks if the continuation escapes.
It is always continuations all the way down.
So, leaving aside the problem of interacting with the OS for I/O, you can do interleaved CPU-bound in a single thread, by instrumenting your code with basically an instruction counter. When it grows a bit too large, stop, reset it, and switch to another task. Erlang does this, although being a functional language, it counts only function calls (no other way to make a loop than to (tail-)call itself). No CPS needed.