gpt4 book ai didi

rust - 为什么 !Send 在 .await 之前被 drop() 丢弃的值意味着 Future 是 !Send?

转载 作者:行者123 更新时间:2023-12-05 03:19:09 25 4
gpt4 key购买 nike

test_use_std_mutex_1test_use_std_mutex_2的逻辑是一样的。为什么一个报错,一个编译成功?

fn main() {
let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2)
.enable_all().build().unwrap();
rt.block_on(async {
let (sen, mut rec) = tokio::sync::mpsc::channel::<()>(1);
// Why can it be compiled by commenting out here? Isn't their logic the same?
tokio::spawn(test_use_std_mutex_1(sen.clone()));
tokio::spawn(test_use_std_mutex_2(sen.clone()));
drop(sen);
let _ = rec.recv().await;
println!("over");
});
}

async fn test_use_std_mutex_1(sen: Sender<()>) {
let _sen = sen;
let mut rwlock_list: Arc<Mutex<LinkedList<String>>> = Default::default();
let mut lock = rwlock_list.lock().unwrap();
println!("push_back hello");
lock.push_back("hello".to_string());
// Is it not deleted here?
drop(lock);
time::sleep(Duration::from_secs(1)).await;
}

async fn test_use_std_mutex_2(sen: Sender<()>) {
let _sen = sen;
let mut rwlock_list: Arc<Mutex<LinkedList<String>>> = Default::default();
{
let mut lock = rwlock_list.lock().unwrap();
println!("push_back hello");
lock.push_back("hello".to_string());
}
time::sleep(Duration::from_secs(1)).await;
}
error: future cannot be sent between threads safely
--> src\main.rs:39:22
|
39 | tokio::spawn(test_use_std_mutex_1(sen.clone()));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ future returned by `test_use_std_mutex_1` is not `Send`
|
= help: within `impl futures_util::Future<Output = ()>`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, LinkedList<std::string::String>>`
note: future is not `Send` as this value is used across an await
--> src\main.rs:55:40
|
50 | let mut lock = rwlock_list.lock().unwrap();
| -------- has type `std::sync::MutexGuard<'_, LinkedList<std::string::String>>` which is not `Send`
...
55 | time::sleep(Duration::from_secs(1)).await;
| ^^^^^^ await occurs here, with `mut lock` maybe used later
56 | }
| - `mut lock` is later dropped here

这是什么原因造成的?

最佳答案

关于rust - 为什么 !Send 在 .await 之前被 drop() 丢弃的值意味着 Future 是 !Send?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73519148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com