Hacker News new | past | comments | ask | show | jobs | submit | page 2 login
How to think about async/await in Rust (cliffle.com)
191 points by mpweiher 11 months ago | hide | past | favorite | 258 comments



"From my perspective, this is the fundamental promise of async fn: easier, composable, explicit state machines."

Honestly, working in embedded... I don't want my state machine hidden like this. I want it up front and explicit, documented, and observable. I want to be able to query components to find out what state they're in. I want to be able to keep metrics on their transitions. I want logging at the transition points. And I want the whole thing specified in code and comments, and I want to be able to see up front how it's using its resources and I want each component to describe its potential state movements. Even better if I can use declarative/formal analysis tools to check them, too (see e.g. stateright)

The risk with the async call-flow pattern is the creeping emergence of new undocumented state transitions, and potential new error states and edge conditions that come from them.


I like this quote. Forgot where I first heard it.

    Threads are for working in parallel, async is for waiting in parallel.
If your app is doing the work, use threads. If something else is doing the work like a database engine or the kernel retrieving a file from disk, use async since your app is just waiting.


Archive, as the original link seems to be unresponsive: https://web.archive.org/web/20230702221952/http://cliffle.co...


I'm confused about this part:

    async fn my_state_machine() {
        set_pin_high();
        defer! { tristate_pin(); }

        sleep_for(Millis(100)).await;

        set_pin_low();
        sleep_for(Millis(100)).await;

        // Pin gets tristated here
    }
> This will ensure that a minimum of 100 ms elapses between our changes to the pin. We can’t impose a maximum using this approach, because – as we saw above – our caller could wait months between stepping our state machine, and that’s part of what we’re signing up for by writing this state machine.

Surely the example code _does_ ensure that both the minimum and the maximum wait times are approximately 100ms between changes to the pin? The functions set_pin_high() and set_pin_low() are just normal functions AIUI; they are not async (are not awaited). In the previous snippets the author used a pending!() macro, but that is not used here.


As someone unfamiliar with Rust and who has almost never used async, this has been a great explanation. Well presented and clear. Thanks!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: