Trying to do a basic parallel sum with Tokio and can't figure it out #5498
Unanswered
ChaseLewis
asked this question in
Q&A
Replies: 2 comments
-
use std::{vec::Vec};
use std::sync::Arc;
use std::ops::Range;
use tokio::sync::RwLock;
async fn sum(vector: Arc<RwLock<Vec<u64>>>, r: Range<usize>) -> u64 {
let readable = vector.read().await;
let mut accumulator = 0 as u64;
for i in r {
accumulator += readable[i];
}
return accumulator;
}
#[tokio::main]
async fn main() {
let values: Arc<RwLock<Vec<u64>>> = Arc::new(RwLock::new((0..4096).collect()));
let mut chunk_size = 0 as usize;
{
let readable = values.read().await;
chunk_size = readable.len() / 4;
}
let futures: Vec<_> = (0..4)
.into_iter()
.map(|i| {
tokio::spawn(sum(values.clone(), i*chunk_size..(i+1)*chunk_size))
})
.collect();
let mut accumulator = 0 as u64;
for f in futures.into_iter() {
accumulator += f.await.unwrap();
}
println!("Sum: {}", accumulator);
} This is a way that works. Is there an easier way? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Tokio isn't really the best way to schedule and distribute cpu-bound work. It is built for predominantly IO-bound workloads. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to see if there is a clean easy way to parallel process array. A pretty standard task. The issue is since the closure needs to take ownership of a reference to the a chunk I can't figure out how to do the task . Surprisingly I couldn't find an example looking around the web without bringing in multiple other libraries .... which seems kinda crazy.
Beta Was this translation helpful? Give feedback.
All reactions