1# event-listener 2 3[![Build](https://github.com/smol-rs/event-listener/workflows/Build%20and%20test/badge.svg)]( 4https://github.com/smol-rs/event-listener/actions) 5[![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( 6https://github.com/smol-rs/event-listener) 7[![Cargo](https://img.shields.io/crates/v/event-listener.svg)]( 8https://crates.io/crates/event-listener) 9[![Documentation](https://docs.rs/event-listener/badge.svg)]( 10https://docs.rs/event-listener) 11 12Notify async tasks or threads. 13 14This is a synchronization primitive similar to [eventcounts] invented by Dmitry Vyukov. 15 16You can use this crate to turn non-blocking data structures into async or blocking data 17structures. See a [simple mutex] implementation that exposes an async and a blocking interface 18for acquiring locks. 19 20[eventcounts]: http://www.1024cores.net/home/lock-free-algorithms/eventcounts 21[simple mutex]: ./examples/mutex.rs 22 23## Examples 24 25Wait until another thread sets a boolean flag: 26 27```rust 28use std::sync::atomic::{AtomicBool, Ordering}; 29use std::sync::Arc; 30use std::thread; 31use std::time::Duration; 32use event_listener::Event; 33 34let flag = Arc::new(AtomicBool::new(false)); 35let event = Arc::new(Event::new()); 36 37// Spawn a thread that will set the flag after 1 second. 38thread::spawn({ 39 let flag = flag.clone(); 40 let event = event.clone(); 41 move || { 42 // Wait for a second. 43 thread::sleep(Duration::from_secs(1)); 44 45 // Set the flag. 46 flag.store(true, Ordering::SeqCst); 47 48 // Notify all listeners that the flag has been set. 49 event.notify(usize::MAX); 50 } 51}); 52 53// Wait until the flag is set. 54loop { 55 // Check the flag. 56 if flag.load(Ordering::SeqCst) { 57 break; 58 } 59 60 // Start listening for events. 61 let listener = event.listen(); 62 63 // Check the flag again after creating the listener. 64 if flag.load(Ordering::SeqCst) { 65 break; 66 } 67 68 // Wait for a notification and continue the loop. 69 listener.wait(); 70} 71``` 72 73## License 74 75Licensed under either of 76 77 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 78 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 79 80at your option. 81 82#### Contribution 83 84Unless you explicitly state otherwise, any contribution intentionally submitted 85for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 86dual licensed as above, without any additional terms or conditions. 87