#slot #signals #signal

apex

为Rust提供的可配置多线程信号和槽实现

3个版本

0.1.2 2020年5月9日
0.1.1 2020年5月9日
0.1.0 2020年5月9日

#43#signals

MIT 协议

18KB
257

为Rust提供的可配置多线程信号和槽实现。内部使用mpsc通道和可配置的事件循环系统,以允许完全的多线程消息处理,而不浪费CPU时间。

示例

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();

依赖项

~420KB