matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.87k stars 109 forks source link

.wait() never wakes up #243

Closed jobafr closed 1 year ago

jobafr commented 1 year ago

Hi,

the documentation for OnceCell::wait() says: "Gets the reference to the underlying value, blocking the current thread until it is set."

If I understand correctly, this should make it possible to use it as a single-shot broadcast channel. However, it seems the method never returns, even after .set has been called by another thread.

Minimal example:

use once_cell; // 1.18.0

const SINGLE_SHOT : once_cell::sync::OnceCell<()> = once_cell::sync::OnceCell::new();

fn main() {
    let h = std::thread::spawn(|| {
        SINGLE_SHOT.wait();
        println!("got it");
    });
    std::thread::sleep_ms(200);
    println!("setting....");
    SINGLE_SHOT.set(()).unwrap();
    println!("value is now set, waiting for the other thread");
    h.join().unwrap();
    println!("joined");
}

Expected output:

setting....
value is now set, waiting for the other thread
got it
joined

Actual output:

setting....
value is now set, waiting for the other thread

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=33d34c94b01fee452a522aea62c2c40f

Is this a bug or am I doing something wrong?

matklad commented 1 year ago

const SINGLE_SHOT :

You want static there

jobafr commented 1 year ago

You're right, I do. Thanks :)