Promises in D
Sebastiaan Koppe
mail at skoppe.eu
Thu Apr 8 07:39:44 UTC 2021
On Thursday, 8 April 2021 at 05:42:28 UTC, Vladimir Panteleev
wrote:
> Thanks!
>
> Looking into this a bit, I understand that this doesn't quite
> attempt to solve the same problems.
Indeed, it is much broader.
> The document and the talk begins about how this is aimed to be
> a tool at doing parallel/asynchronous computations. Promises
> and async/await are mainly concerned about scheduling execution
> of code on the CPU asynchronously while avoiding waiting for
> blocking operations (network or I/O). Everything still runs on
> one thread.
Senders/Receivers doesn't impose a specific execution model, you
can use it on coroutines, threads, fibers, etc. In the
implementation I focused on threads cause that is what we needed,
but there isn't anything preventing from building an fiber
scheduler on top of this.
> I wasn't able to quickly divine if this approach allows
> avoiding the value copy as delegates do. If they do, would you
> mind explaining how (such as in the case that a
> promise/equivalent is resolved immediately, before a result
> handler is attached)?
There is a section in the talk about promises and futures.
https://youtu.be/h-ExnuD6jms?t=686
In short, they are eager. This means that they start running as
soon as possible. That means the setValue of the promise and the
attaching of the continuation can happen concurrently. Therefor
space has to be allocated for the return value, as well as some
sort of synchronization for the continuation handler.
Senders/Receivers on the other hand are lazy. They don't start
until after the receiver has been attached. Because of that it
needs no allocation for the value, doesn't need to type-erase the
continuation, and there is no concurrent access on the
continuation handler.
If you limit your program to a single thread you can avoid the
concurrent access on the continuation handler, but that still
leaves the value the promise produces, you still need to allocate
that on the heap and ref count it.
Because Senders/Receivers are lazy, there is less shared state
and the ownership is simpler. On top of that they can often use
the stack of whoever awaits them.
More information about the Digitalmars-d
mailing list