采用静音的异步递归函数

发布于 2025-02-10 12:33:47 字数 905 浏览 2 评论 0原文

您如何创建一个sync递归函数,以占用静音? Rust声称该代码在等待点上含有互惠码。但是,该值在.await之前已删除。

#[async_recursion]
async fn f(mutex: &Arc<Mutex<u128>>) {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    let value = *unwrapped;
    drop(unwrapped);
    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
    if value < 100 {
        f(mutex);
    }
}

错误

future cannot be sent between threads safely
within `impl futures::Future<Output = ()>`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard<'_, u128>`
required for the cast to the object type `dyn futures::Future<Output = ()> + std::marker::Send`rustc
lib.rs(251, 65): future is not `Send` as this value is used across an await

How do you create an async recursive function that takes a mutex? Rust claims that this code holds a mutex across an await point. However, the value is dropped before the .await.

#[async_recursion]
async fn f(mutex: &Arc<Mutex<u128>>) {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    let value = *unwrapped;
    drop(unwrapped);
    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
    if value < 100 {
        f(mutex);
    }
}

Error

future cannot be sent between threads safely
within `impl futures::Future<Output = ()>`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard<'_, u128>`
required for the cast to the object type `dyn futures::Future<Output = ()> + std::marker::Send`rustc
lib.rs(251, 65): future is not `Send` as this value is used across an await

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫雨熙 2025-02-17 12:33:47

在这种情况下,您可以对代码进行重组以使其未包装无法在上使用

let value = {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    *unwrapped
};
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
if value < 100 {
    f(mutex);
}

如果您无法执行此操作,那么您' d需要做到这一点,这样您就不会返回实现发送未来async_recursion docs指定选项您可以传递到宏以禁用send限制它添加:

#[async_recursion(?Send)]
async fn f(mutex: &Arc<Mutex<u128>>) {
    ...

In this case, you can restructure the code to make it so unwrapped can't be used across an await:

let value = {
    let mut unwrapped = mutex.lock().unwrap();
    *unwrapped += 1;
    *unwrapped
};
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
if value < 100 {
    f(mutex);
}

If you weren't able to do this, then you'd need to make it so you don't return a Future that implements Send. The async_recursion docs specify an option you can pass to the macro to disable the Send bound it adds:

#[async_recursion(?Send)]
async fn f(mutex: &Arc<Mutex<u128>>) {
    ...

(playground)

You wouldn't be able to send such a Future across threads though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文