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
    }

Where Next?

Popular Pragmatic Bookshelf topics Top

jon
Some minor things in the paper edition that says “3 2020” on the title page verso, not mentioned in the book’s errata online: p. 186 But...
New
conradwt
First, the code resources: Page 237: rumbl_umbrella/apps/rumbl/mix.exs Note: That this file is missing. Page 238: rumbl_umbrella/app...
New
cro
I am working on the “Your Turn” for chapter one and building out the restart button talked about on page 27. It recommends looking into ...
New
adamwoolhether
When trying to generate the protobuf .go file, I receive this error: Unknown flag: --go_opt libprotoc 3.12.3 MacOS 11.3.1 Googling ...
New
patoncrispy
I’m new to Rust and am using this book to learn more as well as to feed my interest in game dev. I’ve just finished the flappy dragon exa...
New
jgchristopher
“The ProductLive.Index template calls a helper function, live_component/3, that in turn calls on the modal component. ” Excerpt From: Br...
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
oaklandgit
Hi, I completed chapter 6 but am getting the following error when running: thread 'main' panicked at 'Failed to load texture: IoError(O...
New
dtonhofer
@parrt In the context of Chapter 4.3, the grammar Java.g4, meant to parse Java 6 compilation units, no longer passes ANTLR (currently 4....
New
davetron5000
Hello faithful readers! If you have tried to follow along in the book, you are asked to start up the dev environment via dx/build and ar...
New

Other popular topics Top

DevotionGeo
I know that these benchmarks might not be the exact picture of real-world scenario, but still I expect a Rust web framework performing a ...
New
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
AstonJ
This looks like a stunning keycap set :orange_heart: A LEGENDARY KEYBOARD LIVES ON When you bought an Apple Macintosh computer in the e...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
AstonJ
Seems like a lot of people caught it - just wondered whether any of you did? As far as I know I didn’t, but it wouldn’t surprise me if I...
New
AstonJ
Saw this on TikTok of all places! :lol: Anyone heard of them before? Lite:
New
PragmaticBookshelf
Rails 7 completely redefines what it means to produce fantastic user experiences and provides a way to achieve all the benefits of single...
New
New
AstonJ
Was just curious to see if any were around, found this one: I got 51/100: Not sure if it was meant to buy I am sure at times the b...
New
New

Sub Categories: