[英]Why do std::task, core::task, and tokio::task all exist?
[英]How do I pass these references to a function that spawns a tokio task?
我有一些完全按预期工作的代码:
pub async fn start(num_websockets: i32) {
let messages_received = Arc::new(Mutex::new(0));
let (shutdown_signal, _) = broadcast::channel(1);
let (done, mut wait_for_tasks) = channel::<&str>(1);
tokio::spawn(stats::message_counter(
Arc::clone(&messages_received),
shutdown_signal.subscribe(),
done.clone(),
));
for _i in 0..num_websockets {
let (ws_stream, _) = websocket::connect().await.unwrap();
let (mut write, read) = ws_stream.split();
subscription::subscribe(&mut write, "book.BTC-PERPETUAL.100ms")
.await
.unwrap();
tokio::spawn(websocket::listener(
read,
messages_received.clone(),
shutdown_signal.subscribe(),
done.clone(),
));
}
在 for 循环中,我生成了任意数量的websocket::listener
,它会在接收到shutdown_signal
时关闭,并通过done
让main
知道它们何时完成。
当我尝试将此代码提取到 function 时,如下所示:
...
for _i in 0..num_websockets {
subscribe_and_listen(messages_received.clone(), shutdown_signal.subscribe(), done.clone());
}
...
async fn subscribe_and_listen(messages_received: Arc<Mutex<i32>>,
shutdown_signal: broadcast::Receiver<&str>,
done: mpsc::Sender<&str>) {
let (ws_stream, _) = websocket::connect().await.unwrap();
let (mut write, read) = ws_stream.split();
subscription::subscribe(&mut write, "book.BTC-PERPETUAL.100ms")
.await
.unwrap();
tokio::spawn(
websocket::listener(
read,
messages_received.clone(),
shutdown_signal,
done.clone(),
)
);
}
编译器告诉我:
error[E0759]: `shutdown_signal` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/benchmark.rs:21:9
|
13 | shutdown_signal: broadcast::Receiver<&str>,
| ------------------------- this data with an anonymous lifetime `'_`...
...
21 | / websocket::listener(
22 | | read,
23 | | messages_received.clone(),
24 | | shutdown_signal,
| | --------------- ...is used here...
25 | | done.clone(),
26 | | )
| |_________^
|
note: ...and is required to live as long as `'static` here
--> src/benchmark.rs:20:5
|
20 | tokio::spawn(
| ^^^^^^^^^^^^
note: `'static` lifetime requirement introduced by this bound
--> /Users/b0nes/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.20.0/src/task/spawn.rs:127:28
|
127 | T: Future + Send + 'static,
我尝试了很多东西,但我根本无法将这段代码移动到 function,我真的很想了解如何做到这一点。 在我看来,不需要任何东西是'static
,因为 function 可以完全拥有shutdown_signal.subscribe()
和done.clone()
的结果
解决方案是为通道shutdown_signal
和done
使用String
,或者使用其他满足 'static 的类型,例如 &'static str。
在我的情况下,我实际上不需要提供任何字符串,所以我只是用()
创建了一个频道。
问题是, &str
不能被拥有,但这正是tokio::spawn
任务所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.