相关疑难解决方法(0)

如何在另一个 Tokio 运行时内创建 Tokio 运行时而不会出现“无法从运行时内启动运行时”的错误?

rust_bert用于总结文本。我需要用 设置一个模型rust_bert::pipelines::summarization::SummarizationModel::new,它从互联网上获取模型。它以异步方式执行此操作,tokio并且(我认为)我遇到的问题是我正在另一个 Tokio 运行时中运行 Tokio 运行时,如错误消息所示:

Downloading https://cdn.huggingface.co/facebook/bart-large-cnn/config.json to "/home/(censored)/.cache/.rustbert/bart-cnn/config.json"
thread 'main' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.', /home/(censored)/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.21/src/runtime/enter.rs:38:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Run Code Online (Sandbox Code Playgroud)

我试过与模型同步运行 tokio::task::spawn_blockingtokio::task::block_in_place 但它们都不适合我。block_in_place给出了同样的错误,就像是不存在的,并spawn_blocking没有真正似乎是用我的。我也尝试过summarize_text异步,但这并没有多大帮助。Github 问题 tokio-rs/tokio#2194 和 Reddit 发布 …

rust rust-tokio

6
推荐指数
2
解决办法
3583
查看次数

与lazy_static 一起使用'await' 的替代方法!生锈的宏?

我想在一个项目中使用 Async MongoDB。

不想绕过客户端,因为它需要绕过多个任务和线程。所以我使用惰性静态保留了一个静态客户端。但是我不能在初始化块中使用 await。

我能做些什么来解决这个问题?

也欢迎在没有 lazy_static 的情况下完全不同地做这件事的建议。

use std::env;
use futures::stream::StreamExt;
use mongodb::{
    bson::{doc, Bson},
    options::ClientOptions,
    Client,
};

lazy_static! {
    static ref MONGO: Option<Client> = {
        if let Ok(token) = env::var("MONGO_AUTH") {
            if let Ok(client_options) = ClientOptions::parse(&token).await
                                                                     ^^^^^
            {
                if let Ok(client) = Client::with_options(client_options) {
                    return Some(client);
                }
            }
        }
        return None;
    };
}
Run Code Online (Sandbox Code Playgroud)

asynchronous mongodb rust lazy-static

5
推荐指数
1
解决办法
1011
查看次数

Rust 的 Lazy init(OnceCell crate)并非在所有地方都有效

我正在用Serenity用 Rust 编写一个不和谐的机器人。为了填充一些嵌入标头,我需要与机器人相关的信息(用户和所有者,以下称为BOT),并且我尝试使用Once_cellLazy板条箱中的结构来实现这一点。

问题是这些BOT数据只能使用 Serenity 的 Http 模块的异步函数来查询,而我正在努力使其工作。

我设置了一些斜杠命令,每个命令都有自己的处理函数。当我BOT从这些处理程序函数之一取消引用(这就是应该评估它(仅一次),对吧?)时,我的Lazy闭包在它遇到的第一个函数上阻塞.await

另一方面,当我BOTmain(tokio async)取消引用时,它才起作用。

因此,以下代码在从特定斜杠命令处理程序 (BoxedFuture) 取消引用时打印“0,1,2,3” BOTmain但仅打印“0,1”:

use once_cell::sync::Lazy;
use serenity::{http::Http, model::user::User};

pub struct Bot {
    pub user: User,
    pub owner: User,
}

pub static BOT: Lazy<Bot> = Lazy::new(|| {
    println!("0");
    let http_client = Http::new(env!("DISCORD_BOT_TOKEN"));

    futures::executor::block_on(async {
        println!("1");
        let user = http_client
            .get_current_user()
            .await
            .expect("An HTTP client error occured")
            .into();

        println!("2"); …
Run Code Online (Sandbox Code Playgroud)

asynchronous lazy-loading rust discord

0
推荐指数
1
解决办法
1059
查看次数