by divan · 7y ago · 0 comments
Like in real life I can do something synchronously (meaning paying full attention), or I can do the same task asynchronously (watching youtube videos in the background while cooking, for example), but it's still up to me. Being "async" is not a property of the "watching youtube" action, it's the property of the caller running this action.
That's the reason why CSP-based concurrency models really works well for me – it's just so easy to map mental models of system's behaviour from the head directly to the code. You have function/process and it's up to you how do you run it and/or how synchronize with it later.
Async/await concept so popular in modern languages is totally nuts in this aspect. Maybe it's just me, but I find myself adding more accidental complexity to the code just to make async/await functions work nicely, especially for simple cases where I don't need concurrency at all, but one "async" function creeps in.
async/await aren't strictly necessary, but to avoid them you need one of:
1. a sufficiently smart compiler with whole program compilation, or
2. to compile two versions of every function, an async variant and a sync variant, or
3. every async wait captures the whole stack, thus wasting a lot of memory.
Async/await is basically a new sort of calling convention, where the program doesn't run in direct style but in continuation-passing style. This permits massive concurrency scaling with little memory overhead, but there other tradeoffs as per above.
Async/await makes perfect sense for Rust which wants to provide zero-overhead abstractions.
1. They may not have access to the representation the subroutines store their state, as it may be platform dependent (e.g. if you're targeting LLVM you may not have access to that representation).
2. They may not track their pointers, and so find it hard to move chunks of stack around if they have internal pointers into the stack.
3. They may want to enable some specific optimizations in the special (and rare, especially when IO is involved) case of a monomorphic calls to shallow coroutines. This requires that the representation of the subroutine's state be available as a high-level node for the compiler to change.
For a statically compiled language that produces machine code and prefers stack allocation and has strict constraints on copying references, it is not so easy.
This is a lesson that we all learned during the NPTL/NGPT era [1] and have subsequently forgotten and will have to relearn.
Anyway, I don't think anyone has forgotten those lessons, but they're not very relevant to modern managed runtimes. (also mioco seems to be single-threaded)
Unless you have some approach I haven't heard of, in which case, please provide a link!
However, the paradox you have to manage here is this: if you make this sequential/parallel determination pretty high up in the code so that there is a lot of sequential code right after an async part (async can call sync all it wants), then very little of your code is altered, but now you have the green threads problem - one long CPU-bound task that doesn’t yield.
At least with Rust, if you’ve partitioned your data properly then there can be several threads of execution running tasks on unrelated data, but in Javascript you will be punished for trying to consolidate the async bits in this fashion.
[1] true non-tail recursion is a problem of course, but it is ok for the compiler to give up if it can't statically prove that the recursion depth is less than a documented maximum.
edit: rewording
For example: convert an internal iterator to an external one (in pseudo C++, yes, yes, I know):
// This is a bog standard template function. Cont can be anything
// here as long as it is callable. It literally does the same thing
// as for_each
template<class Cont, class Iter>
Cont inside_out(Iter begin, Iter end, Cont yield){
// as long as yield lifetime is confined to the scope of
// inside_out; when Cont
// ends up being some compiler internal (possibly unique) magic
// type it should be possible to CPS convert both inside_out and
// for_each. Both rust and C++ monomorphize templates anyway so
// instantiating dedicated CPS variant is not a problem.
std::for_each(begin, end, [&](auto&& x) { yield(x); });
// for various reasons we need to return the continuation here. A
// proper language would tail call to it.
return yield;
}
...
// this is basically call/cc. It uses magic to get the current
// continuation, then invokes its first argument with it and the
// remaining arguments. The current function need to be
// Note: template functions are not first class in
// C++, but we take some liberty here.
auto cont = continuationify(inside_out, my_vec.begin(), y_vec.end());
while(not cont.done())
std::cout << cont();
if inside_out was not templated, but instead Cont was type erased (a trait object in rust parlance), then continuatinify would need to allocate a dedicated stack and fall back to good old userspace context switching (the compiler is welcome to pierce through the type erasure layer and optimize anyway, but it would not be a guaranteed optimization).Rust is close enough to C++ that it would work in the same way. I've been planning to write a paper for the C++ committee to add fire to the current coroutine controversy and proposing something like the above (which would unify stackless and stackful coroutines).
int bar(int i) { return i+1; }
/* bar takes a implicit return address in [esp+0] */
noreturn foo((*ra)(int),int x)
{
/* where (*)(RetType) is a return address */
int y = bar(x); /* x86 call pushes eip */
ra return bar(y); /* pseudo-tail-call (push ra) */
}
int quux(int x)
{
(*ret)(int); ret = (return); /* get implicit RA */
foo(ret,x);
} // unreachable
You'd also need to adjust the stack and/or frame pointer though, which is probably going to be the hard part.The choice of `async`-vs-not is not the one you describe. What we label with `async` is a particular compilation style that makes the function interruptible in userspace, in exchange for making synchronous and recursive execution a bit more complicated. This style is important because it gives you event loop-style concurrency without the performance costs of threads (kernel or userspace/green/etc).
However, this compilation style still leaves the choice you describe up to the caller. Most languages seem to reverse the default choice syntactically, but you can still synchronously block on a call to an async function or run it concurrently with something else. It just so happens to be useful primarily for doing the latter, so it gets lumped in with it. (And we get unfortunate misunderstandings like "What Color is Your Function?" that miss this point.)
As an example of a language that doesn't reverse the defaults, look at Kotlin's `suspend fun`s. While they still have `async`-like callee annotations to control the compilation style, a simple function call behaves the same regardless of the callee, and you instead use various `spawn` or CSP-like APIs to get concurrency.
If changing the keyword and making the defaults match threads/CSP isn't enough, perhaps viewing the annotation as part of an effect system would help? The thing being tracked here is "this function can suspend itself mid-execution," and a good effect system even functions be polymorphic over things like this. For example, an effect-polymorphic function passed a closure or interface can automatically take on the effects of its callees, simplifying the program somewhat if you're faced with viral async-ness.
Steve Klabnick provided some useful context on that thread for the Rust decision specifically. More generally though, you've nailed my primary misgiving:
> Synchronous or asynchronous is something up to the caller to the decide – not to the function itself.
Erlang/Elixir and Go place the decision with the caller, not the callee. That just seems much more sensible.
An alternative is perhaps to see async/await as dataflow going through the awkward teenager stage. Maybe one day we'll wake up and languages in general will have fully embraced dataflow variables as first order constructs.
I dislike how this stuff "infect" all your code calls:
https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...
And the problem is rust is that we already have other stuff that infest everything: Borrows, mutability, ownership...
I don't think anyone disagrees that the annotation of these concepts play a very heavy role in the type system and cognitive burden of writing code. But there are really three alternatives you can do here:
1. Do nothing, and rely on programmers to manually remember how to do all the necessary bookkeeping themselves. This is better known as "C", and the sheer amount of CVEs and other problems in code written in C is ample evidence that this approach just doesn't work.
2. Make the runtime do the automatic programming. JS is the exemplar of the pattern here. But this approach requires the VM to do garbage collection itself (which adds uncertain hidden overhead), generate code to handle arbitrary shapes (which can result in hidden performance cliffs). And heavily dynamic languages also turn compiler errors (such as fat-fingering a variable name) into runtime errors that can be accidentally ignored.
3. Shift the annotation into a mandatory part of the language, as Rust does. It makes the cognitive burden of writing the code higher, it requires more coding, but the resulting code tends to have the highest performance and lowest bugs of any of these approaches.
The tradeoff you have to make is between "no safety", "compile-time safety", and "runtime safety"; the costs you have to weigh are the costs of testing to uncover bugs, the costs of programmer cognitive and annotation burden, and the (often hidden!) costs of the runtime to dynamically enforce the conditions.
Rust has chosen to live in the camp of low implicit runtime cost and high compile-time safety, and it is really to pay the price for that with extra annotation burden. You may disagree with that choice, but it is a conscious choice that has been made.
This is what I want. I just not like the specific implementation of awaits. I'm not much against it: i could live with it (I have used C#/F#/JS that is similar).
The thing is that still split the world even if you don't want it.
I think CSP/Actors have lesser cognitive load but of course I don't know how make them work without a runtime..
Unlike in JS, it really doesn't. In Rust, at any point you have the option to run a Future returned from an async function to completion in a sync function (which blocks the thread) and stop the spread of async.
While also making your software more resilient to failure because error handling is easier as you can contain the code into small processes, communicate through messaging, let processes fail, and handle/restart them from the supervisor. Using the OTP supervisor model encourages you to think through those things, like error handling and the lifecycle of your code, so it doesn't impact other parts of your running app. A lot of exception handling in other languages is often bolted-on after-the-fact and isn't part of the typical design, at least for more inexperienced developers.
It's best to commit fully to either a full-featured VM or Rust/c low level OS style IMO.
The latter group can still support a more complex actor model with libraries and frameworks (ie, https://actix.rs/) which is more flexible but nothing beats having it be the 'standard' philosophy of the language and fully baked into the runtime.
LoadWasher() (sync)
washerRunning = RunWasher() (async)
var cleaning = CleanKitchen() (async)
wetClothes = await washerRunning;
LoadDryer(wetClothes)
clothesToIron = await RunDryer() // while we're awaiting we walk back up the stack and can continue cleaning the kitchen until the dryer is finished
IronClothes(clothesToIron) // this is just happening synchronously
await cleaning //last job to do so we need to make sure we finish!
Don't know if that helps, but I think it's an interesting analogy LoadWasher() | RunWasher() | LoadDryer() | RunDryer() | IronClothes()
CleanKitchen()
where `|` is piping the output of one operation into the next one (as per *nix shell). The two lines are independent and so can be scheduled according to resources available.Doing so makes the inherent dependencies trivially clear. It doesn't matter which are "long" running and which aren't: it's not possible to run the washer until it's been loaded. Using async/await conflates two things:
1. What's "long" running, for some definition of "long" (--> make it async)
2. What's dependent on what (await)
--
EDIT: fix formatting & added missing "RunDryer()" step
Then wrap it in a try/catch or pattern match the result to handle the various errors different errors...
No, the point is you don't _need_ async. At least not as a language primitive. Instead, one expresses directly where the data dependencies lie. If an operation in a pipeline blocks, the runtime is at liberty to switch to another task. That already happens today, whether in language runtimes (e.g. Node) or the underlying OS. I don't need to tell the runtime "this operation might block". It already knows.
Instead, we've explicitly defined intent: when `RunWasher()` finishes, `LoadDryer()`. It doesn't matter if the washer takes one micro second or one hour; I can't load the dryer until it's done.
>Then wrap it in a try/catch or pattern match the result to handle the various errors different errors...
True, error handling is missing. But then it's not in the parent example either. The requirements aren't fundamentally different in either case.
If you replace the machines with people, it makes much more sense for the function definition to define what is and isn't synchronous. If you have to do all the chores yourself, just call the functions synchronously. If you have family members you can delegate some work to, you can call the functions asynchronously and wait for them to complete while you're doing your own work (or twiddling your thumbs).
Elixir allows you to do this very cleanly. https://hexdocs.pm/elixir/Task.html#content
If I do what I've always done in rust, which in use threads, I get lovely easy parallelization. Async only seems useful when your program doesn't do anything non trivial, but just dispatches to other things, as any one function that takes a long time blocks all other async functions until completion?
- What is the best approach to encapsulate blocking I/O in future-rs? — https://stackoverflow.com/q/41932137/155423
I'd rather dirty the signatures of blocking/synchronous methods then of the rest.
Namely in platforms like Node the convention is to not do synchronous I/O and as a communication tool - everything that doesn't use async/await is promised to never block or perform I/O.
You might claim it's a lower level of abstraction but it makes concurrency a _lot_ simpler and it's why often when I write go I have to write 35 lines for something that would take me 5 in C#, Python, JavaScript or now Rust.
How do you deal with a situations when you have non-async/await code, and then you need to call just one function, which happened to be "async", and you can't do until you mark all your functions async as well? I find myself in this situation too often with Dart/Flutter, and it's especially embarrassing experience as it happens usually with a simple parts of code, where I don't need concurrency at all (like, get local directory name and store file to it). This "forced refactoring" also hits language design corners like "you can't call async functions" in constructor or `iniState()` and I end up writing async wrappers and other helpers functions just to make the whole thing work.
> it makes concurrency a _lot_ simpler
I find people put different meaning in the word "simpler". Do you mean that code requires less lines/chars to write or that it's easier to read and understand (those are totally different properties, often conflicting)?
It'd be way more convenient if Node just assumed it couldn't carry on with the next operation until the current one was done, even if the current operation is async I/O—feel free to go off and process something else, just no more of my code—unless instructed otherwise. IOW, caller decides, yes. I 100% do not understand the appeal of a system where you have to specify that you do want the next instruction to wait on the result of the previous one. "But you'll block node's single thread during your I/O!" no, it can go do something else, just no more of this particular line of logic in my code unless I specifically tell it otherwise, thanks.
Caller decides is both easier to follow and more useful.
But to be clear, "it'll block Node's single thread!" is not the reason for explicit await. The reason for explicit await is to guarantee that after calling a function foo(), only the state that foo() changes could have changed. Whereas after awaiting on an async function bar(), or any other promise, literally any state-mutating code in the entire application might have run.
Obviously plenty of languages have this problem and deal with it, usually with locks like in Go and Java, or by banning shared mutable state entirely and only allowing message-passing for communication between concurrent "lines of logic" like in Erlang. (As far as I understand Go basically tries to get the best of both worlds by strongly encouraging message-passing, with locks intended only for advanced situations like custom concurrent data structures.)
But there's no way for Node to change to either of those models without breaking every single nontrivial piece of code ever written in it. And apparently Rust intentionally chose not to go with those models because they require a runtime and make compatibility with C very difficult, well-known advantages over Go.
This depends on what do you want to happen. Do you want to block on the one async function, or do you want to turn your current function into async and propagate the asyncness to your caller?
Both options are available to you in Rust.
Just call the poll function on your Future.
Just because Javascript sucks doesn't mean the similar feature in Rust does too. :)
Each method now returns a Task, and each method name ought to have a suffix of 'Async'. It sucks that changing this will require all consumers to also modify their signatures as well. But I understand why it is necessary, the compiler needs to mark each 'step' in the asynchronous function to create a kind of state machine.
As for calling async from sync, I imagine you just create a runtime and block on it.
I don't think that's true. See fs.readFileSync for example. You could say that's an exceptional case (which I think it is), but it means that there's no "promise" that functions without async/await don't perform I/O.
That's a good thing :]
If `fs` was promise-aware and top-level await existed, it would be a different conversation. As-is, for writing a one-off script, avoiding callback hell is pretty nice.
If I text you, I expect an asynchronous response. It's ok if you get back to me 3 hours later (well, context-dependent).
If I call you, ask you a question, and then you wait 3 hours before giving me a response, I've been sitting there blocked for 3 hours, unable to get any more work done, because I asked for a synchronous response and got an asynchronous one. Even worse, if you try and give me the response over text, I won't see it because I have the phone pressed to my ear and now I'm blocked forever.
---
The caller and callee have to agree on whether the communication is synchronous or asynchronous. Asking for synchronous and getting asynchronous doesn't work. Asking for asynchronous and getting synchronous kind of works, but that's not truly synchronous, that's just asynchronous with zero delay before getting the response. Or even worse, asking for asynchronous (and giving you a completion handler to fire) and you fire it synchronously before returning control to me, that way lies madness. Don't do that.
val result = runBlocking {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
one.await() + two.await()
}
https://kotlinlang.org/docs/reference/coroutines/composing-s...EDIT: actually this was wishful thinking, since both functions would block the main thread. The functions need to be modified to "suspend" for this to be truly async.
My ideal language would be something like Kotlin suspend semantics, except ALL functions were implicitly "suspend" functions. If that's even possible...
let result = executor::block_on({
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
one.await + two.await
});
See examples in:- What is the purpose of async/await in Rust? — https://stackoverflow.com/a/52835926/155423
And why this might be a bad idea in:
- What is the best approach to encapsulate blocking I/O in future-rs? — https://stackoverflow.com/q/41932137/155423
What you need is:
use futures::join;
let result = executor::block_on({
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
let (one, two) = join!(one, two);
one + two
});
I feel like this might be a common stumbling block and hope there will be a Clippy check for this or something.In the spirit of getting it right, your code is missing an `await` and `join` is back to a function in alpha18. Here's the currently working (this time tested!) code:
#![feature(async_await)]
use futures::{executor, future}; // 0.3.0-alpha.18
fn main() {
let result = executor::block_on(async {
let one = async { do_something_useful_one() };
let two = async { do_something_useful_two() };
let (one, two) = future::join(one, two).await;
one + two
});
println!("{}", result);
}
fn do_something_useful_one() -> i32 { 1 }
fn do_something_useful_two() -> i32 { 2 }And the syntax is surprisingly similar, especially considering we are supposedly comparing a low level language to a high level one.
See the sibling comment [1] where I actually tested and ran the code, finally. ;-). I was unaware that Kotlin would race two `async` blocks, so we had to use the `join` combinator here.
This is a exactly how I feel as well and I write Rust code every day.
But no matter, I will suck it up. The language is evolving and I think async/await has, seemingly, been one of the biggest divisive feature the community has faced. I will still use as there are so many other benefits this language brings.
Perhaps because you hadn't had the displeasure to work with callbacks, or promises? Which async/await greatly simplifies.
That's probably the real reason why so many people are so happy and vocal about "simplicity" of async/await – after experiencing concurrency only with callbacks in JS, async/await looks like a blessing.
I think of await to mean "When this code is combined with all the other code that needs to be executed asynchronously on the event loop, this code will not be able to progress until this thing we are waiting on finishes. The event loop can therefore use this hint to schedule things and keep the processors busy."
I think I built up a good understanding of how this kind of a system works with futures 0.1 and tokio. It took some time but it all clicked together for me. But as for async/await as language features I'm satisfied to just let it be magic. I don't care to look under the covers at this point. I know it's similar to how futures worked, and I trust the rust team weaved it together well.
One of the problems with async is that it's viral. Make a function async and your entire call graph has to be made async, unless they handle the future manually without await. Async introduces a new "colour" to the language.
I absolutely agree that asynchronicity should be the provenance of the caller. If you look at typical code in languages with async/await such as JavaScript and C#, awaiting is the common case. So if async causes your code to be littered with awaits anyway, it makes more sense to make awaiting the default (just like it's the default for the rest of the language) and "deferring" the exception. Call it "defer" or something.
(As an aside, I was always disappointed that Go's "go" doesn't return a future, or that indeed there's no "future" support in the standard library. Instead you have to muck about with WaitGroup and ErrGroup and channels, which introduces sequencing even in places that don't need it. Sometimes you just want to spawn N goroutines and then collect all their results in whatever order, and short-circuit then if one of them fails. The inability to forcibly terminate goroutines is another wart here, requiring Context cancellation and careful context management to get right.)
In most languages, including Rust, async functions can call synchronous functions, so this isn't entirely true.
> unless they handle the future manually without await.
At some point, the futures are always handled manually, e.g., via the run-time, or in Rust case, by scheduling on an Executor, which is nothing but a fancy name for a library that manually handles a lot of futures.
> If you look at typical code in languages with async/await such as JavaScript and C#, awaiting is the common case.
Do you have any example of code that uses await more than synchronous functions ?
> So if async causes your code to be littered with awaits anyway, it makes more sense to make awaiting the default (just like it's the default for the rest of the language) and "deferring" the exception. Call it "defer" or something.
If the purpose is just to change the defaults, then you'd need `defer vec.len()` to access the length of a vector, or `defer array[i]` to index into an array, or `defer obj.foo` to access the field `foo` of an object, ... unless you want to make all of those operations `async`.
If you make await the default and add a `defer` operation that doesn't awaits, then it's hard to imagine how the resulting code could contain less `defer` annotations than `await` ones.
At that point you might choose one of the many non-zero-cost solutions to removing the async distinction, and call it a day like Go does.
First, async infects the call graph, that is, going up the stack. Not down.
Secondly, by "manually" I mean using the future API -- and_then() and so forth.
Thirdly, "defer vec.len()" doesn't make sense unless you want to execute it asynchronously and get a future. And that doesn't make sense unless you know it to be an expensive operation you want to run concurrently. I'm proposing that the hypothetical "defer" would act like Go's "go", except it would return a future.
Lastly, my point was that most code is serial and relies on awaits. For example, if you're doing a name lookup, then opening a socket, then writing to it -- three async calls that must be serialized with await because the actions depend on each other. Not awaiting is needed when you intend to use the future for some purpose, such as adding to a queue or putting in a map, or perhaps you're doing N connections that you put in a vector to ask the runtime to wait for all of them (does Rust's await syntax support awaiting multiple futures?). But most high-level "user" code doesn't juggle futures, it just awaits whenever it needs a result. From a language-ergonomics perspective, it makes more sense to optimize for the common case.
I've never written any async/await code in Rust, but I've written plenty in JavaScript, and it's the same story.
No, but you use a join combinator, which itself returns a future, that you can then await.
But that was not what I was arguing. Rather, I was arguing that await is more common than capturing the raw future. Case in point: The article, where all of the "real code" snippets rely purely on await.
What I proposed was that async functions would always be automatically awaited unless invoked with "defer", because most code is expressed as a series of invocations that use the return value of the function call.
There are times you want to store the raw future as some kind of state (for example, in a GraphQL server you might "resolve" the GraphQL tree as futures), or wait for multiple futures, or similar, but those are, in my experience, the exceptions, not the norm. Most code is:
let v1 = do1().await;
let v2 = do2(v1).await;
// etc.
In other words, serial.You can "handle the future manually without await" very easily, it's just one function call. The same sort of thing is available in most other languages with async/await- you can prevent async from going up the call stack by synchronously blocking on a future instead of awaiting it.
The caller is absolutely in charge of whether something runs asynchronously. The only difference is a syntactic default- and in fact some languages even make async functions calls default to synchronous execution. For example take a look at Kotlin's `suspend fun`s.
Not in Rust. Or C#. Or any language except JavaScript.
In Rust, a synchronous function can call and block on an async function with executor::block_on(). C# has Task.Wait() and Task.Result(). Python 3 has asyncio.run(). Scala has Await.ready() and Await.result(). Kotlin has runBlocking {}.
Also, blocking on a future is trivial (just call poll).
So I would argue that async/await does a better job of leaving it up to the caller to decide: use await if you want async, use poll if you want sync.
CSP as implemented in languages like Go is just threads, but with an idiosyncratic implementation.
What about the stack size? I guess the default is about 4 MB, compared to a few kB in Erlang or Rust. This implies a virtual memory usage 100x or 1000x higher. I understand the unused virtual pages in each stack will never be mapped to physical memory, but isn't this putting a lot of pressure on the virtual memory system? I'd be curious to read a real world benchmark on this topic.
This doesn't work with Rusts implementation, because the functions have slightly different semantics and limitations.
E.g. an async function can't be recursive, since that would lead to a Future type of infinite size.
Async functions also don't necessarily run to completion like normal functions. They can instead also return at any .await point, which are implicit cancellation points. That means if someone just adds an async modifier to a function and some .await calls to methods inside it the result might not be correct anymore, since not all code in the function is guaranteed to be run anymore.
The cancellation mechanism was an explicit choice of the design - it would probably have been possible too to make async functions always run to completion and to thereby avoid the semantic difference.
But "wait until there's eol, than call this callback" or its cousin the future which is "when complete, read here to find the callback(s) to call" which let's you fill in the callback after the call, that's inherently an async call. Same way sending a letter forces you to wait. Sure you could stand by the mailbox until the reply arrives, but that's just converting the async call to synchronous by waiting.
Though I don't really see how futures are that different from a cps, especially if you view them as chaining .then calls, which are exactly continuations. Await just let's you drop some syntax, and unify scopes.
In other words, synchronous procedures are essentially locally CPU-bound, while asynchronous procedures are bound by I/O, network or IO/network/CPU of remote servers.
Async functions are the most efficient way to support asynchronous procedures, while non-blocking non-async functions are the most efficient way to support synchronous procedures.
There are also adapters to turn synchronous function into asynchronous ones, and to turn asynchronous functions into blocking non-async functions, although they should only be used when unavoidable, especiallly the latter.
https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9...
It’s not, however you do need the entire runtime to be in on it. That’s what Erlang, Go or gevent (for python) do: normal concurrency is in user land and normal IO uses « async ». The code itself looks / is synchronous, it just multiplexes in userland before doing so on OS threads.
I strongly recommend to check it out. I was absolutely mind-blown when saw this talk (without prior knowledge about Go), and that changed my life quite literally.
https://www.youtube.com/watch?v=QDDwwePbDtw
I did a few concurrency related projects (see "Visualizing concurrency in Go" https://divan.dev/posts/go_concurrency_visualize/, for example), and it's way more easier to reason about and work with than any other concurrency approaches I've seen so far.
Languages with fibers figure ou execution suspend points and physical core assignment for you and abstract it all away. So physically they're doing the same thing as async, just without all the cruft.
Rust decided not to go with fibers to avoid having a runtime. I still disagree with this because they already do reference counting, not every worthwhile abstraction is zero cost.
Refcounting is a library feature, does not require a runtime, and has no impact on code not using it.
Fibers is a langage feature, does require a runtime, and impacts everything.
Rust actually stripped out its support for fibers as its community moved its usage downwards the stack. In much the same way it stripped out « core » support for GC/RC (the @ sigil) or internal (smalltalk/ruby-style) iteration.
(I'd also be very skeptical of the 2% figure; where did you get that from?)
Remember, "zero cost" means "zero additional cost", everything has a cost.
Now that rust has async, couldn't they make fibers an opt-in replacement for threads? Your libraries use async, but you can handle those calls with fibers. Fiber support is compiled into your code but not the libraries
> Your libraries use async, but you can handle those calls with fibers. Fiber support is compiled into your code but not the libraries
We tried this! Making the attempt is actually one of the biggest reasons that we decided to remove green threads from Rust; it brought in tons of disadvantages and no real advantages.
I consider Rust to be an antithesis to your remarks because it has realoy good tools to prevent concurrency issues and yet still wants it.
I think on a deeper level it's because there are times where the thread isn't really doing anything and is instead waiting, and that time could be better apent doing something else. That requires sync, either with callbacks, promises or sync/await.
First he starts with a rant about the color of a function. In that sense, all typed languages have a color, aka the type of their return parameters. Sure, there a advantages to dynamic languages, but they're going out of fashion now for some good reasons.
Then he lists 5 more specific drawbacks of async code in 2015 Javascript 2015. All 5 aren't issues in Rust.
#1. Every function has a color: that's how typed languages work
#2. The way you call a function depends on its color: the rust compiler doesn't let you get this wrong and provides cut and paste corrections when you do
#3. You can only call a red function from within another red function: Use Future#poll
#4. Red functions are more painful to call: This is in reference to callback syntax in old node.js code and is fixed by the await sugar even in modern Javascript
#5. Some core library functions are red: The clause "that we are unable to write ourselves" is untrue in Rust; you should never have a need to drop down into C to write anything. And this is really just a variant of #3; if it's trivial to convert async to sync this wouldn't be an issue.
Now `async`, you could see it as an implementation detail that you need in order to get much better performance...
You can't (in safe Rust) easily replicate what async does for you because it understands how to handle borrows across yield points, which turn into self borrows when you turn the stack into a concrete object in Rust. That's not really an issue in garbage collected languages so it's not quite as much of a necessity to have a specific keyword, but it's still inconvenient in most languages to write everything in CPS or use combinators to acquire thunks.
As for why you would want a function that's not asynchronous... well, various reasons, but one is performance. Creating a thunk and then sending it to a runtime which decides what to do with it (or polling) usually has some overhead compared to linearly calling a function on the stack.
Another reason is that, in Rust, top-level asynchronous functions normally need to be quite conservative with what they own if you want to use them with an actual asynchronous runtime--many of them like to send the thunks between threads in a static thread pool, which limits you to thread safe constructs and owned (or static-borrowed) data. As a result, even if there was no overhead for using an asynchronous function synchronously, you would still in practice have to either sacrifice performance and generality by keeping your data owned and thread-safe (to make things work with thread pools), or embrace all the usual stuff you would do in synchronous code (like borrow things from a previous stack frame) and lose the ability to use your async function at the top level in most existing asynchronous runtimes. So from that standpoint, it's not really up to the caller. This is again not really an issue in garbage collected languages that only allow references to managed, heap-allocated objects.
There are more reasons than that (being able to efficiently call out to blocking C APIs, wanting to use builtin thread locals across function calls without worrying about how the function call is going to be handled, current issues with recursion, etc.). They may be considered artifacts of the implementation or otherwise resolvable--I'm not necessarily saying they aren't--but they are reasons in practice why you want to have synchronous functions available.
So tl;dr I think most people's immediate intuitions about how async/await should just be sugar, or async should be up to the caller (i.e. all functions should be async), don't straightforwardly apply to Rust even if they are valid for most other languages.