Why `drop()` not work for some cases about "future cannot be sent between threads safely"

Sorry friend, I need some help. I don't understand why drop() cannot remove the compile error:

#![allow(unused_variables, dead_code)]

use std::rc::Rc;

fn foo(rc: &Rc<u8>) {
    ()
}

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        let v = Rc::new(42u8);
        
        // foo(&v);    // why uncomment this line will cause compile error?
        drop(v);       // ... and `v` never across an await point
        
        async{1}.await;
    });
}

Playground

And the following code can work as expect:

#![allow(unused_variables, dead_code)]

use std::rc::Rc;

fn foo(rc: &Rc<u8>) {
    ()
}

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        {
            let v = Rc::new(42u8);
        
            foo(&v);
        }   // use block syntax to replace `drop(v)` and it work... but why?
        
        async{1}.await;
    });
}

Playground


And I also check drop() effective in almost the same scenario.

#![allow(unused_variables, dead_code)]

use std::rc::Rc;

fn foo(rc: &Rc<u8>) {
    ()
}

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        let v = Rc::new(42u8);
        
        drop(v);       // comment this line make compile error so drop is effective.
        
        async{1}.await;
    });
}

Playground

Can someone give me an explain? Thanks.

1 Like

until someone gives you a proper answer, you could maybe look into why Arc works

EDIT: nevermind, my bad.

Arc works without dropping, since it's Send, that's not surprising.

Actually, I'm not sure why the last example in OP works - I remember moving out of bindings (including drop) to not influence the analysis for "is this value being held over await". Maybe something was special-cased to work?..

1 Like

The Rust compiler is too stupid to accept this kind of code, sorry.

I don't know why it works in the last example. I would have expected it to fail. I guess the compiler is able to handle cases where you never take a reference to the value.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.