#slot #signals #signal

apex

A configurable, multi-threaded signals and slots implementation for Rust

3 releases

0.1.2 May 9, 2020
0.1.1 May 9, 2020
0.1.0 May 9, 2020

#43 in #signals

MIT license

18KB
257 lines

A configurable, multi-threaded signals and slots implementation for Rust. Uses mpsc channels and a configurable event-loop-like system internally to allow for fully multi-threaded message handling without wasting cpu time.

Example

use apex::{Signal, Slot};
use std::sync::{ Arc, atomic::{
    AtomicBool, AtomicI32, Ordering }
};
use std::time::Duration;

//create a slot that will poll continuously for 10 milliseconds in 10 millisecond intervals
let mut slot = Slot::<i32>::new(Duration::from_millis(10), Duration::from_millis(10));
let mut sig = Signal::<i32>::new();

let multiply = Arc::new(AtomicBool::new(true));
let multiply_cloned = multiply.clone();
let num = Arc::new(AtomicI32::new(5));
let num_cloned = num.clone();

slot.connect(&mut sig);
let callback = move |t: i32| {
    if multiply_cloned.load(Ordering::Relaxed) {
        let mut temp = num_cloned.load(Ordering::Relaxed);
        temp *= t;
        num_cloned.store(temp, Ordering::Release);
    }
    else {
        let mut temp = num_cloned.load(Ordering::Relaxed);
        temp /= t;
        num_cloned.store(temp, Ordering::Relaxed);
    }
};
slot.open(callback);

sig.emit(5);
//in practice this would be using some sort of timing synchronization mechanism,
//but this is good enough for this simple test/example to make sure the 'emit' has finished
//before 'assert' gets called
std::thread::sleep(std::time::Duration::from_millis(10));

let multiplied = num.load(Ordering::Relaxed);
assert_eq!(multiplied, 25);
multiply.store(false, Ordering::Relaxed);
//ditto above
std::thread::sleep(std::time::Duration::from_millis(10));

sig.emit(25);
//ditto above
std::thread::sleep(std::time::Duration::from_millis(10));

let divided = num.load(Ordering::Relaxed);
assert_eq!(divided, 1);
slot.close();

Dependencies

~420KB