Red

Red

Rust Brain Teasers: Comments on puzzle 19/async (page 82-)

An open discussion about this particular puzzle on asynchronous code, since I’m only learning and I may have overlooked something.

1.) About tokio, you either have to declare the main as

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { ... }

or if main is something else, it also possible to use its own block_on (or other alternative) to launch the asynchronous code. In this case, you have to enable the time “reactor” to avoid a panic:

fn main() {
    let rt = runtime::Builder::new_multi_thread()
        .enable_time()
        .build()
        .unwrap();

    rt.block_on(test()).unwrap();
}

with, for example

    async fn test() -> Result<(), Box<dyn std::error::Error>> {
        join!(count_and_wait(1), count_and_wait(2), count_and_wait(3));
        Ok(())
    }

or directly inserting an async block: rt.block_on(async { ... }).

2.) There is another alternative to using tokio::time::sleep or a thread-oriented approach.

The problem comes from using a thread function, which is not meant for this sort of asynchronous pattern as very well explained pages 82 and 85. We actually get the same issue in other languages like Kotlin. There is no .await and so no real “break” that will allow to switch to another async code.

There is an asynchronous async_std::task::sleep function which supports .await and will give the expected outcome:

    use async_std::task;

    async fn count_and_wait(n: u64) -> u64 {
        println!("starting {}", n);
        task::sleep(Duration::from_millis(n * 100)).await;
        println!("returning {}", n);
        n
    }

Popular Prag Prog topics Top

simonpeter
When I try the command to create a pair of migration files I get an error. user=&gt; (create-migration "guestbook") Execution error (Ill...
New
jdufour
Hello! On page xix of the preface, it says there is a community forum "… for help if your’re stuck on one of the exercises in this book… ...
New
mikecargal
Title: Hands-on Rust: question about get_component (page 295) (feel free to respond. “You dug you’re own hole… good luck”) I have somet...
New
herminiotorres
Hi @Margaret , On page VII the book tells us the example and snippets will be all using Elixir version 1.11 But on page 3 almost the en...
New
brunogirin
When I run the coverage example to report on missing lines, I get: pytest --cov=cards --report=term-missing ch7 ERROR: usage: pytest [op...
New
New
dsmith42
Hey there, I’m enjoying this book and have learned a few things alredayd. However, in Chapter 4 I believe we are meant to see the “&gt;...
New
adamwoolhether
Is there any place where we can discuss the solutions to some of the exercises? I can figure most of them out, but am having trouble with...
New
akraut
The markup used to display the uploaded image results in a Phoenix.LiveView.HTMLTokenizer.ParseError error. lib/pento_web/live/product_l...
New
Keton
When running the program in chapter 8, “Implementing Combat”, the printout Health before attack was never printed so I assumed something ...
New

Other popular topics Top

brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
DevotionGeo
I know that -t flag is used along with -i flag for getting an interactive shell. But I cannot digest what the man page for docker run com...
New
foxtrottwist
Here’s our thread for the Keyboardio Atreus. It is a mechanical keyboard based on and a slight update of the original Atreus (Keyboardio ...
New
AstonJ
Do the test and post your score :nerd_face: :keyboard: If possible, please add info such as the keyboard you’re using, the layout (Qw...
New
PragmaticBookshelf
“Finding the Boundaries” Hero’s Journey with Noel Rappin @noelrappin Even when you’re ultimately right about what the future ho...
New
AstonJ
In case anyone else is wondering why Ruby 3 doesn’t show when you do asdf list-all ruby :man_facepalming: do this first: asdf plugin-upd...
New
wmnnd
Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New
gagan7995
API 4 Path: /user/following/ Method: GET Description: Returns the list of all names of people whom the user follows Response [ { ...
New
foxtrottwist
A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New

Latest in PragProg

View all threads ❯