2020/12/16

2020 Perl Advent Calendar - Day 16

<< First | < Prev | Next >

Over the past couple of weeks we've seen lots of syntax for managing asynchronous functions using the async and await keywords. While some things have been new (such as awaiting on a future returned by the needs_all or wait_any constructors), much of it has been the same as regular synchronous Perl syntax just with functions declared using async sub and called in await expressions. All of the usual forms of control flow - conditional if blocks, while and foreach loops, and so on - have all been exactly the same.

This contrasts with the original blog post series from seven years ago which explained Futures as they looked before the creation of async/await syntax. That spent many days building up to the day 22 post which had a long list of examples of synchronous vs. future-based control flow, looking different on each side even though they were trying to do fundamentally the same logic. In yesterday's post we also saw some more complex code structures that were necessary to create an HTTP client, when async/await is not available.

Day 23 of the original series then summarized a lot of advantages in terms of new things that can be done, such as the concurrency constructors. These advantages still hold when using async/await, though now we can use the additional neatness of such syntax to make the code even more readable.

The entire series last time culminated in day 24's retrospective overview; parts of which I shall quote here:

Futures allow the control- and data-flow structure of a program to be inherently expressed together, describing the dependency relationships between individual operations.
This makes for convenient control-flow that coincides with data-flow; ensuring that the result of an operation is passed to the next operation in the sequence at the time it is executed.
[This is] in contrast to the split nature of other kinds of concurrency control, such as callback functions or locks and mutexes, which generally only manage the flow of control and require other techniques like lexical variables shared between multiple closures to provide the data flow. Such sharing of mutable state between domains of concurrency is the source of many kinds of concurrency bug which cannot happen with Futures.

When working with async/await syntax, all of these advantages remain because async and await are keywords that inherently deal with futures. What they give, via the basic mechanism of suspending and resuming a function around a pending future, is a way to still use regular Perl syntax to form recognisable code shapes. Asynchronous code written using async/await syntax is thus inherently more comprehensible by Perl programmers, because it follows existing patterns, while still allowing the extra abilities of concurrency and asynchronous behaviour provided by futures.

<< First | < Prev | Next >

No comments:

Post a Comment