
[英]How do I pass these references to a function that spawns a tokio task?
[英]How to find number of active tokio task?
我想获得正在运行的 tokio 任务的数量。 在 python 中,我可以使用len(asyncio.all_tasks())
返回当前运行循环的未完成任务。 我想知道 tokio 中的任何等价物。
这是一个示例代码:
use std::time::Duration;
use tokio; // 1.24.1
use tokio::time::sleep;
fn active_tasks() -> usize {
todo!("get active task somehow")
}
#[tokio::main]
async fn main() {
tokio::spawn(async { sleep(Duration::from_secs(5)).await });
tokio::spawn(async { sleep(Duration::from_secs(1)).await });
tokio::spawn(async { sleep(Duration::from_secs(3)).await });
println!("t = 0, running = {}", active_tasks());
sleep(Duration::from_secs(2)).await;
println!("t = 2, running = {}", active_tasks());
sleep(Duration::from_secs(4)).await;
println!("t = 6, running = {}", active_tasks());
}
我希望上面程序的 output 打印活动任务的数量,因为 main 本身是一个 tokio 任务,我不会惊讶地发现以下 output:
t = 0, running = 4
t = 2, running = 3
t = 6, running = 1
如果需要, active_tasks()
可以是异步 function。
我希望不稳定的RuntimeMetrics能够为您解决这个问题,但它似乎是为不同的目的而设计的。 我不相信 Tokio 能够为您处理这件事。
话虽如此,这是实现类似结果的潜在解决方案:
use std::{
future::Future,
sync::{Arc, Mutex},
time::Duration,
};
use tokio::time::sleep;
struct ThreadManager {
thread_count: Arc<Mutex<usize>>,
}
impl ThreadManager {
#[must_use]
fn new() -> Self {
Self {
thread_count: Arc::new(Mutex::new(0)),
}
}
fn spawn<T>(&self, future: T)
where
T: Future + Send + 'static,
T::Output: Send + 'static,
{
// Increment the internal count just before the thread starts.
let count = Arc::clone(&self.thread_count);
*count.lock().unwrap() += 1;
tokio::spawn(async move {
let result = future.await;
// Once we've executed the future, let's decrement this thread.
*count.lock().unwrap() -= 1;
result
});
}
fn thread_count(&self) -> usize {
// Get a copy of the current thread count.
*Arc::clone(&self.thread_count).lock().unwrap()
}
}
#[tokio::main]
async fn main() {
let manager = ThreadManager::new();
manager.spawn(async { sleep(Duration::from_secs(5)).await });
manager.spawn(async { sleep(Duration::from_secs(1)).await });
manager.spawn(async { sleep(Duration::from_secs(3)).await });
println!("t = 0, running = {}", manager.thread_count());
sleep(Duration::from_secs(2)).await;
println!("t = 2, running = {}", manager.thread_count());
sleep(Duration::from_secs(4)).await;
println!("t = 6, running = {}", manager.thread_count());
}
结果是:
t = 0, running = 3
t = 2, running = 2
t = 6, running = 0
这将大致完成您所描述的内容。 为了更接近您要查找的内容,您可以将管理器与lazy_static
结合起来,并将其包装在名为spawn
或其他名称的 function 中。 您也可以从 1 开始计数器以计算主线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.