标签: rust-tokio

我如何在不等待的情况下运行未来?(生锈)

我有一些异步函数

async fn get_player(name: String, i: Instant) -> Option<Player> {
// some code here that returns a player structs
}
Run Code Online (Sandbox Code Playgroud)

在我的主函数中,我想在循环中同时运行上述函数,该函数大约需要 1 秒才能完成,并且我需要运行它至少 50 次,因此我想让它同时运行该函数 50 次。在我的主函数中,我有一个lazy_static自定义Client结构,该结构不应创建多次。

主功能

#[tokio::main]
async fn main() {
    client.init().await;

    println!("start");
    for i in 0..10 {
        println!("{}", i);
        let now = Instant::now();

        tokio::spawn(async move  {
            client.get_player("jay".to_string(), now).await;
        });
    }
    loop {}
}
Run Code Online (Sandbox Code Playgroud)

我传递即时的原因是因为在我的 get_player 函数中我有一个 println!() 只打印执行时间。

上面的 main 方法每个函数调用大约需要 500ms,但是下面的代码只需要 100ms。

#[tokio::main]
async fn maain(){
    client.init().await;

    for i in 0..10 {
        let now …
Run Code Online (Sandbox Code Playgroud)

rust rust-tokio rust-async-std

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

如何为枚举类型(rust、postgres)实现 tokio_postgres::types::ToSql

我需要为枚举类型实现 tokio_postgres::types::ToSql (rust 和 db 作为枚举实现),但我不知道如何...

例子

enum Flag {MyFlag1, MyFlag2, MyFlag3};
// on postgres db :
//    CREATE TYPE flag AS ENUM ('my_flag_1', 'my_flag_2', 'my_flag_3');

impl ToSql for Flag {
  fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
    // ???
  }
  fn accepts(ty: &Type) -> bool {
    // ???
  }
}
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

rust rust-tokio tokio-postgres

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

如果我立即等待,为什么“tokio::spawn”需要“static”生命周期?

我想并行运行两个Future,如果可能的话在不同的线程中运行:

try_join!(
  tokio::spawn(fut1), // fut1 is not 'static
  tokio::spawn(fut2)
)?;
Run Code Online (Sandbox Code Playgroud)

如果我的理解是正确的,tokio::spawn则需要 aFuture'static,因为执行是立即开始的,并且不能保证未来不会超出当前范围。

然而,就我而言,我立即将await它们发送出去,所以我知道它不会超过当前的范围。

我的推理正确吗?如果不是,在我的情况下传递非参数有什么不安全的地方'static

rust rust-tokio

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

rust 一次从多个渠道接收消息

我有一个Vec<tokio::sync::broadcast::Receiver<String>>(基本上是通道接收器的向量)。我想订阅所有这些内容并从他们那里获取消息。我该怎么做?

rust rust-tokio

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

如何在Rust中选择未来和流?

我刚开始在Rust尝试期货/ tokio.我可以用期货或只用流来做基本的事情.我想知道如何在未来和流之间进行选择.

如何将tokio文档中的玩具问题扩展到用于tokio_timer::Timer执行定时HTTPS请求?

extern crate futures;
extern crate native_tls;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_tls;

use std::io;
use std::net::ToSocketAddrs;

use futures::Future;
use native_tls::TlsConnector;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_tls::TlsConnectorExt;

fn main() {
    let mut core = Core::new().unwrap();
    let handle = core.handle();
    let addr = "www.rust-lang.org:443".to_socket_addrs().unwrap().next().unwrap();

    let cx = TlsConnector::builder().unwrap().build().unwrap();
    let socket = TcpStream::connect(&addr, &handle);

    let tls_handshake = socket.and_then(|socket| {
        let tls = cx.connect_async("www.rust-lang.org", socket);
        tls.map_err(|e| {
            io::Error::new(io::ErrorKind::Other, e)
        })
    });
    let request = tls_handshake.and_then(|socket| { …
Run Code Online (Sandbox Code Playgroud)

future stream rust rust-tokio

4
推荐指数
1
解决办法
1934
查看次数

如何在Rust中使用hyper,tokio和future设置HTTP请求的超时?

如何使用异步Hyper(> = 0.11)设置HTTP请求的超时?

以下是没有超时的代码示例:

extern crate hyper;
extern crate tokio_core;
extern crate futures;

use futures::Future;
use hyper::Client;
use tokio_core::reactor::Core;

fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::new(&core.handle());

    let uri = "http://stackoverflow.com".parse().unwrap();
    let work = client.get(uri).map(|res| {
        res.status()
    });

    match core.run(work) {
        Ok(status) => println!("Status: {}", status),
        Err(e) => println!("Error: {:?}", e)
    }
}
Run Code Online (Sandbox Code Playgroud)

timeout http rust hyper rust-tokio

4
推荐指数
2
解决办法
1630
查看次数

如何在 #[no_std] 环境中使用 Tokio Reactor?

我正在尝试在 Tock OS 嵌入式操作系统上实现期货。我正在尝试在环境中使用Tokio#[no_std]

我的Cargo.toml文件看起来像这样:

[package]
name = "nrf52dk"
version = "0.1.0"
authors = ["Tock Project Developers <tock-dev@googlegroups.com>"]
build = "build.rs"

[profile.dev]
panic = "abort"
lto = true
opt-level = "z"
debug = true

[profile.release]
panic = "abort"
lto = true
opt-level = "z"
debug = true

[dependencies]
cortexm4 = { path = "../../arch/cortex-m4" }
capsules = { path = "../../capsules" }
kernel = { path = "../../kernel" }
nrf52 = { path = "../../chips/nrf52" …
Run Code Online (Sandbox Code Playgroud)

future rust rust-cargo rust-tokio

4
推荐指数
1
解决办法
1210
查看次数

如何在Tokio中使用async / await语法?

我正在尝试对Rust中的进程使用异步/等待。我正在使用tokiotokio-process

#![feature(await_macro, async_await, futures_api)]

extern crate tokio;
extern crate tokio_process;

use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run_async(main_async());
}

async fn main_async() {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output_async();
    let s = await!(out);
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

#![feature(await_macro, async_await, futures_api)]

extern crate tokio;
extern crate tokio_process;

use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run_async(main_async());
}

async fn main_async() {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output_async();
    let s = await!(out);
}
Run Code Online (Sandbox Code Playgroud)

我该如何正确处理?

rust async-await rust-tokio

4
推荐指数
1
解决办法
1802
查看次数

tokio 在 Rust 中加入多个任务

想象一下,一些 future 存储在一个Vec长度由运行时决定的 a 中,你应该同时加入这些 future,你应该怎么做?

显然,通过文档中的示例tokio::join,手动指定每个长度Vec可能是,如 1,2,3,... 并处理可观的案例应该工作。

extern crate tokio;

let v = Vec::new();
v.push(future_1);

// directly or indirectly you push many futures to the vector
 
v.push(future_N);

// to join these futures concurrently one possible way is 

if v.len() == 0 {}
if v.len() == 1 { join!(v.pop()); }
if v.len() == 2 { join!(v.pop(), v.pop() ); }
// ...
Run Code Online (Sandbox Code Playgroud)

我还注意到 tokio::join! 当我使用类似的语法时,将列表作为文档中的参数

tokio::join!(v);
Run Code Online (Sandbox Code Playgroud)

或类似的东西

tokio::join![ v ] /  tokio::join![ v[..] ] …
Run Code Online (Sandbox Code Playgroud)

rust rust-tokio tokio

4
推荐指数
3
解决办法
4587
查看次数

如何使用 Tokio 远程关闭正在运行的任务

我有一个正在接收数据的 UDP 套接字

pub async fn start()  -> Result<(), std::io::Error> {
    loop {
        let mut data  = vec![0; 1024];
        socket.recv_from(&mut data).await?;
    }
}
Run Code Online (Sandbox Code Playgroud)

.await当没有数据进入时,此代码当前被阻塞。我想从我的主线程优雅地关闭我的服务器,那么我如何向.await它发送一个信号,让它停止睡眠并关闭呢?

rust rust-tokio

4
推荐指数
1
解决办法
1140
查看次数