18 stable releases

2.5.1 Sep 22, 2020
2.4.0 Aug 20, 2020
2.3.0 Jul 31, 2020
2.0.1 Jun 24, 2020
1.2.0 May 25, 2020

#106 in Asynchronous

Download history 53490/week @ 2020-11-02 52767/week @ 2020-11-09 57815/week @ 2020-11-16 53878/week @ 2020-11-23 57749/week @ 2020-11-30 56448/week @ 2020-12-07 58892/week @ 2020-12-14 42221/week @ 2020-12-21 39134/week @ 2020-12-28 60932/week @ 2021-01-04 65122/week @ 2021-01-11 64056/week @ 2021-01-18 67025/week @ 2021-01-25 69604/week @ 2021-02-01 65262/week @ 2021-02-08 68163/week @ 2021-02-15

99,398 downloads per month
Used in 1,142 crates (32 directly)

Apache-2.0 OR MIT

35KB
442 lines

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.

No runtime deps