Description
Proposal
Problem statement
OnceCell
is useful for synchronizing write-once data, but it does not have any blocking methods that allow other threads to wait for this data.
Motivating examples or use cases
Sometimes it can be useful to allow the end of computation to return with a value across thread boundaries, when joining may not be acceptable. For example, rayon::spawn does not have a return value that allows for easy returning. Other applications are nested spawning, or cases where a worker thread should return a value (and unblock the parent thread) then continue going without joining.
The example from once_cell shows the basic structure:
use once_cell::sync::OnceCell;
let mut cell = std::sync::Arc::new(OnceCell::new());
let t = std::thread::spawn({
let cell = std::sync::Arc::clone(&cell);
move || cell.set(92).unwrap()
});
// Returns immediately, but might return None.
let _value_or_none = cell.get();
// Will return 92, but might block until the other thread does `.set`.
let value: &u32 = cell.wait();
assert_eq!(*value, 92);
t.join().unwrap();
Solution sketch
Add the following:
impl OnceLock {
/// Block the current thread until the value is set, then return it
fn wait(&self) -> &T;
}
Alternatives
Approximating this behavior with other synchronization primitives, e.g. Barrier
to wait for the thread and Mutex
to store the return value, or just manually parking (which this method is a thin wrapper around).
Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.