33 stable releases (4 major)

5.4.0 Jan 8, 2025
5.3.1 May 29, 2024
5.3.0 Apr 5, 2024
5.2.0 Feb 29, 2024
1.2.0 May 25, 2020

#18 in Concurrency

Download history 2039581/week @ 2024-12-03 2248807/week @ 2024-12-10 1841816/week @ 2024-12-17 862560/week @ 2024-12-24 1254879/week @ 2024-12-31 2243264/week @ 2025-01-07 2239464/week @ 2025-01-14 2218806/week @ 2025-01-21 2304936/week @ 2025-01-28 2599938/week @ 2025-02-04 2623478/week @ 2025-02-11 2653081/week @ 2025-02-18 2748440/week @ 2025-02-25 3197915/week @ 2025-03-04 3145902/week @ 2025-03-11 3309132/week @ 2025-03-18

12,880,182 downloads per month
Used in 9,694 crates (124 directly)

Apache-2.0 OR MIT

145KB
2.5K SLoC

event-listener

Build License Cargo Documentation

Notify async tasks or threads.

This is a synchronization primitive similar to eventcounts invented by Dmitry Vyukov.

You can use this crate to turn non-blocking data structures into async or blocking data structures. See a simple mutex implementation that exposes an async and a blocking interface for acquiring locks.

Examples

Wait until another thread sets a boolean flag:

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use event_listener::Event;

let flag = Arc::new(AtomicBool::new(false));
let event = Arc::new(Event::new());

// Spawn a thread that will set the flag after 1 second.
thread::spawn({
    let flag = flag.clone();
    let event = event.clone();
    move || {
        // Wait for a second.
        thread::sleep(Duration::from_secs(1));

        // Set the flag.
        flag.store(true, Ordering::SeqCst);

        // Notify all listeners that the flag has been set.
        event.notify(usize::MAX);
    }
});

// Wait until the flag is set.
loop {
    // Check the flag.
    if flag.load(Ordering::SeqCst) {
        break;
    }

    // Start listening for events.
    let listener = event.listen();

    // Check the flag again after creating the listener.
    if flag.load(Ordering::SeqCst) {
        break;
    }

    // Wait for a notification and continue the loop.
    listener.wait();
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.2–23MB
~299K SLoC