2024-02-12 15:51:37 +01:00
|
|
|
use satrs::pool::{PoolGuard, PoolProvider, StaticMemoryPool, StaticPoolConfig, StoreAddr};
|
2023-01-11 10:30:03 +01:00
|
|
|
use std::ops::DerefMut;
|
|
|
|
use std::sync::mpsc;
|
|
|
|
use std::sync::mpsc::{Receiver, Sender};
|
|
|
|
use std::sync::{Arc, RwLock};
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
const DUMMY_DATA: [u8; 4] = [0, 1, 2, 3];
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn threaded_usage() {
|
2024-02-12 11:35:10 +01:00
|
|
|
let pool_cfg = StaticPoolConfig::new(vec![(16, 6), (32, 3), (8, 12)], false);
|
2024-02-03 13:41:51 +01:00
|
|
|
let shared_pool = Arc::new(RwLock::new(StaticMemoryPool::new(pool_cfg)));
|
2023-01-11 10:30:03 +01:00
|
|
|
let shared_clone = shared_pool.clone();
|
|
|
|
let (tx, rx): (Sender<StoreAddr>, Receiver<StoreAddr>) = mpsc::channel();
|
|
|
|
let jh0 = thread::spawn(move || {
|
|
|
|
let mut dummy = shared_pool.write().unwrap();
|
|
|
|
let addr = dummy.add(&DUMMY_DATA).expect("Writing data failed");
|
|
|
|
tx.send(addr).expect("Sending store address failed");
|
|
|
|
});
|
|
|
|
|
|
|
|
let jh1 = thread::spawn(move || {
|
|
|
|
let addr;
|
|
|
|
{
|
|
|
|
addr = rx.recv().expect("Receiving store address failed");
|
2023-01-27 00:04:56 +01:00
|
|
|
let mut pool_access = shared_clone.write().unwrap();
|
2023-01-11 10:30:03 +01:00
|
|
|
let pg = PoolGuard::new(pool_access.deref_mut(), addr);
|
2024-02-10 11:59:26 +01:00
|
|
|
let mut read_buf: [u8; 4] = [0; 4];
|
|
|
|
let read_bytes = pg.read(&mut read_buf).expect("Reading failed");
|
|
|
|
assert_eq!(read_buf, DUMMY_DATA);
|
|
|
|
assert_eq!(read_bytes, 4);
|
2023-01-11 10:30:03 +01:00
|
|
|
}
|
2023-01-27 00:04:56 +01:00
|
|
|
let pool_access = shared_clone.read().unwrap();
|
2023-01-11 10:30:03 +01:00
|
|
|
assert!(!pool_access.has_element_at(&addr).expect("Invalid address"));
|
|
|
|
});
|
|
|
|
jh0.join().unwrap();
|
|
|
|
jh1.join().unwrap();
|
|
|
|
}
|