-
Greetings! How can I #[tokio::main]
async fn main() {
let foo = Foo::spawn();
for ecx in 0..10 {
foo.add(ecx.to_string()).await;
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
}
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
struct Foo {
data: std::sync::Arc<tokio::sync::RwLock<Vec<String>>>,
}
impl Foo {
pub fn spawn() -> Self {
let data: std::sync::Arc<tokio::sync::RwLock<_>> = Default::default();
tokio::task::spawn_blocking({
let data = data.clone();
move || {
tokio::runtime::Handle::current().block_on(print_loop(data));
}
});
Self { data }
}
pub async fn add(&self, str: String) {
self.data.write().await.push(str);
}
}
async fn print_loop(data: std::sync::Arc<tokio::sync::RwLock<Vec<String>>>) {
loop {
println!("data: {:?}", data.read().await);
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Is there a particular reason this needs to be spawned as a blocking task? If you are spawning a task which does async stuff interleaved with some data processing, you are probably better of just spawning this as a normal task. |
Beta Was this translation helpful? Give feedback.
-
You should simply be using |
Beta Was this translation helpful? Give feedback.
-
If this is causing problems when run in the same runtime as your other tasks, I would consider using multiple runtimes. That can often work better when this is the case. |
Beta Was this translation helpful? Give feedback.
You should simply be using
tokio::spawn
here.