About whether D / rust / golang can be popular.

Jacob Carlborg doob at me.com
Thu Nov 26 14:18:55 UTC 2020

On Thursday, 26 November 2020 at 09:49:51 UTC, Ola Fosheim 
Grostad wrote:

> Isnt await just syntactic sugar for a promise/future?

No, not really, but it's used together with promises or they're 
used under the hood.

> If you can provide an example of what await should expand into 
> then I might be able to add it to my experimental D compiler 
> and you could then write a DIP.

Async/await is basically a coroutine. It allows a function to be 
suspended and resumed. Here's an example of how the code could 
look like in D:

async int foo()
     await sleep(1.seconds); // simulate work that takes long time
     return 1;

async int bar()
     return 2;

async void main()
     auto a = foo();
     auto b = bar();

     writeln(await a + await b);

The output of the above would be:


The control flow is something like this:

1. `foo` is called
2. `foo` is awaiting for `sleep`
3. `sleep` returns a promise which is not fulfilled
4. This causes `foo` to suspend (return) and control comes back 
to `main`
5. `bar` is called
6. `bar` has no suspension points (awaits) so this is more or 
less a synchronous function
7. "bar" is printed
8. `bar` returns a fulfilled promise with the value `2`
9. Control comes back to `main`
10. "main" is printed
11. `main` awaits `a`. If the `a` promise is not fulfilled at 
this point `main` is suspended
12. `foo` is resumed at some point in the future
13. "foo" is printed
14. `foo` returns a fulfilled promise with the value `1`
15. `main` is now resumed since `a` has been fulfilled
16. `main` awaits `b`
17. `b` is already fulfilled, which means `main` doesn't have to 
18. The addition is performed
19. "3" is printed

I'm not entirely sure on when `foo` will be resumed. Probably 
decided by a scheduler in the runtime.

To have the full experience of async/await, an event loop in the 
runtime is necessary and non-blocking IO.

When a function is suspended, all its state (stack and registers) 
need to be saved. When it's later resumed, the state need to be 
restored. I'm not entirely sure how async/await functions are 
different from fibers, which already exists in the D runtime.

/Jacob Carlborg

More information about the Digitalmars-d mailing list