The rng
crate is neither Sync
nor Send
, so the rng::thread_rng can not cross the .await point. What is the simplest and beautiful way to generate random numbers in async rust?
Generating A lot of numbers beforehead and then use them is ugly.
The rng
crate is neither Sync
nor Send
, so the rng::thread_rng can not cross the .await point. What is the simplest and beautiful way to generate random numbers in async rust?
Generating A lot of numbers beforehead and then use them is ugly.
From the tokio Discord server
let random = rand::random::<i64>();
or
let random = {
let mut rng = rand::thread_rng();
rng.gen::<i64>()
}
"make sure the rng variable falls out of scope before you use an await"
Getting a new rng handle is cheap. A rng will be created once per thread (when used), and after that ThreadRng::default
only uses LocalKey::with and Rc::clone. Do you need to keep the previous state so the number sequence is repeatable?
© 2022 - 2024 — McMap. All rights reserved.
thread_rng
seems to compile being transferred across await in this playground example. I'm not sure what's up with that. – Elaelaboratelet mut rng: StdRng = SeedableRng::from_entropy()
, as shown in this answer. That will give you something that is not just a handle to a thread-local and should be Send+Sync. – Elaelaboratemain()
because main itself gets run in the main thread, which is why Tokio can get away with not requiring that the future it produces beSend
. However, if you try something liketokio::spawn(async { foo().await })
, it will fail to compile, as expected. – Elaelaborate