我有一些异步函数
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) 我需要为枚举类型实现 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)
有人能帮我吗?
我想并行运行两个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?
我有一个Vec<tokio::sync::broadcast::Receiver<String>>(基本上是通道接收器的向量)。我想订阅所有这些内容并从他们那里获取消息。我该怎么做?
我刚开始在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) 如何使用异步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) 我正在尝试在 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) 我正在尝试对Rust中的进程使用异步/等待。我正在使用tokio和tokio-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)
我该如何正确处理?
想象一下,一些 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) 我有一个正在接收数据的 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 ×10
rust-tokio ×10
future ×2
async-await ×1
http ×1
hyper ×1
rust-cargo ×1
stream ×1
timeout ×1
tokio ×1