You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
drop function does not end the lifetime of a variable in in async block
I tried this code:
asyncfnhello(){println!("hello");}
tokio::spawn(asyncmove{letmut rng = rand::thread_rng();let v = rng.gen_range(0..100);drop(rng);hello().await;
v
});
The compiler compiles it with an error
error: future cannot be sent between threads safely
--> src/main.rs:6:26
|
6 | let t = tokio::spawn(async move {
| __________________________^
7 | | let mut rng = rand::thread_rng();
8 | | let v = rng.gen_range(0..100);
9 | | drop(rng);
10 | | hello().await;
11 | | v
12 | | });
| |_____^ future created by async block is not `Send`
|
= help: within `[async block@src/main.rs:6:26: 12:6]`, the trait `std::marker::Send` is not implemented for `Rc<UnsafeCell<ReseedingRng<rand_chacha::chacha::ChaCha12Core, OsRng>>>`
note: future is not `Send` as this value is used across an await
--> src/main.rs:10:16
|
7 | let mut rng = rand::thread_rng();
| ------- has type `ThreadRng` which is not `Send`
...
10 | hello().await;
| ^^^^^^ await occurs here, with `mut rng` maybe used later
11 | v
12 | });
| - `mut rng` is later dropped here
note: required by a bound in `tokio::spawn`
--> /Users/jefffffyang/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/tokio-1.21.2/src/task/spawn.rs:127:21
|
127 | T: Future + Send + 'static,
| ^^^^ required by this bound in `spawn`
I dropped the rng variable in line 9, but the compiler says rng is dropped in line 12. I also write the following code to confirm it is caused by the drop function:
tokio::spawn(asyncmove{let v = {letmut rng = rand::thread_rng();
rng.gen_range(0..100)};hello().await;
v
});
In the above function, rng is dropped by the compiler implicitly. It works well.
Meta
rustc --version --verbose:
rustc 1.71.0-nightly (ce5919fce 2023-05-15)
The text was updated successfully, but these errors were encountered:
drop
function does not end the lifetime of a variable in in async blockI tried this code:
The compiler compiles it with an error
I dropped the
rng
variable in line 9, but the compiler saysrng
is dropped in line 12. I also write the following code to confirm it is caused by thedrop
function:In the above function,
rng
is dropped by the compiler implicitly. It works well.Meta
rustc --version --verbose
:The text was updated successfully, but these errors were encountered: