Singleflight (Rust)
Topics: concurrency, deduplication
Problem
Implement Group<T>, which collapses concurrent calls that share a key into a single execution —
while one call is in flight, other callers for the same key wait and receive its result.
impl<T: Clone> Group<T> {
pub fn new() -> Self;
pub fn do_call<F: FnOnce() -> Result<T, String>>(&self, key: &str, f: F) -> (Result<T, String>, bool);
}
- Dedup in flight: if N threads call
do_call(key, …) while a call for key is running, f
runs once; all N receive the same result.
- Shared flag: the returned
bool is true when the result was shared with at least one other
caller. A lone caller gets false.
- Distinct keys run independently and concurrently.
- After completion the key is cleared, so a later call re-runs
f.
Errors are shared too — model them as Err(String).
Hint: a Mutex<HashMap<String, Arc<Call>>> where each Call carries a Mutex<state> + Condvar
lets late callers block until the leader finishes and notifies them.
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.