31 stable releases (4 major)

5.3.0 Apr 5, 2024
5.2.0 Feb 29, 2024
4.0.3 Jan 6, 2024
4.0.1 Dec 19, 2023
1.2.0 May 25, 2020

#71 in Asynchronous

Download history 1176561/week @ 2024-02-02 1206149/week @ 2024-02-09 1264871/week @ 2024-02-16 1339080/week @ 2024-02-23 1418909/week @ 2024-03-01 1406254/week @ 2024-03-08 1438960/week @ 2024-03-15 1457037/week @ 2024-03-22 1456974/week @ 2024-03-29 1528231/week @ 2024-04-05 1559624/week @ 2024-04-12 1585617/week @ 2024-04-19 1526886/week @ 2024-04-26 1568030/week @ 2024-05-03 1714021/week @ 2024-05-10 1358911/week @ 2024-05-17

6,450,553 downloads per month
Used in 7,528 crates (106 directly)

Apache-2.0 OR MIT

140KB
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–27MB
~359K SLoC