我有一个 tokio 核心,其主要任务是运行 websocket(客户端)。当我从服务器收到一些消息时,我想执行一个新任务来更新一些数据。下面是一个最小的失败示例:
use tokio_core::reactor::{Core, Handle};
use futures::future::Future;
use futures::future;
struct Client {
handle: Handle,
data: usize,
}
impl Client {
fn update_data(&mut self) {
// spawn a new task that updates the data
self.handle.spawn(future::ok(()).and_then(|x| {
self.data += 1; // error here
future::ok(())
}));
}
}
fn main() {
let mut runtime = Core::new().unwrap();
let mut client = Client {
handle: runtime.handle(),
data: 0,
};
let task = future::ok::<(), ()>(()).and_then(|_| {
// under some conditions (omitted), we update the …Run Code Online (Sandbox Code Playgroud) tokio::spawn此 MWE 显示了in循环的使用for in。注释的代码sleepy_futures.push(sleepy.sleep_n(2));工作正常,但不运行/轮询异步函数。
基本上,我想同时运行一堆异步函数。我很高兴更改实现Sleepy或使用其他库/技术。
pub struct Sleepy;
impl Sleepy {
pub async fn sleep_n(self: &Self, n: u64) -> String {
sleep(Duration::from_secs(n));
"test".to_string()
}
}
#[tokio::main(core_threads = 4)]
async fn main() {
let sleepy = Sleepy{};
let mut sleepy_futures = vec::Vec::new();
for _ in 0..5 {
// sleepy_futures.push(sleepy.sleep_n(2));
sleepy_futures.push(tokio::task::spawn(sleepy.sleep_n(2)));
}
let results = futures::future::join_all(sleepy_futures).await;
for result in results {
println!("{}", result.unwrap())
}
}
Run Code Online (Sandbox Code Playgroud) 我试图编译以下看似简单的代码,但出现错误:
use std::io::Error;
#[derive(Debug)]
struct NetworkConfig {
bind: String,
node_key_file: String,
}
async fn network_handler(network_config: &NetworkConfig) -> Result<(), Error> {
Ok(())
}
async fn run(network_config: &NetworkConfig) -> Result<(), Error> {
let network_config_copy = network_config.clone();
tokio::spawn(async move {
network_handler(&network_config_copy).await
}).await?
}
Run Code Online (Sandbox Code Playgroud)
use std::io::Error;
#[derive(Debug)]
struct NetworkConfig {
bind: String,
node_key_file: String,
}
async fn network_handler(network_config: &NetworkConfig) -> Result<(), Error> {
Ok(())
}
async fn run(network_config: &NetworkConfig) -> Result<(), Error> {
let network_config_copy = network_config.clone();
tokio::spawn(async move {
network_handler(&network_config_copy).await
}).await?
}
Run Code Online (Sandbox Code Playgroud)
从之前关于该主题的讨论和示例中,我了解到传递对 …