Generic Concurrent Runner (Rust)
Topics: concurrency, generics
Problem
Run a function over many inputs with bounded concurrency, preserving order:
pub fn run<T, R, F>(tasks: Vec<T>, workers: usize, cancel: &Cancel, f: F) -> Vec<Result<R, RunError>>
where T: Send, R: Send, F: Fn(T) -> Result<R, String> + Sync;
f runs on each task with at most workers threads at a time.
- Results come back in task order, regardless of completion order.
- A task error is collected (
Err(Failed(..))) and does not cancel the others.
- If the
Cancel token is set, tasks that haven't started yet return Err(Cancelled) without
running f.
The Go version takes a context.Context; this port uses a small Cancel token (new / cancel
/ is_cancelled) for the same cooperative cancellation.
Hint: std::thread::scope lets the workers borrow f and a shared Mutex<VecDeque<(usize, T)>>;
write each result into results[idx] so ordering is automatic.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.