fabaccess-bffh/runtime/lightproc/examples/proc_run.rs

51 lines
1.4 KiB
Rust
Raw Normal View History

2021-11-14 17:50:59 +01:00
use crossbeam::channel;
use futures_executor as executor;
use lightproc::prelude::*;
use std::future::Future;
use std::sync::Arc;
use std::thread;
use std::thread::JoinHandle;
2021-11-14 17:50:59 +01:00
use std::time::Duration;
fn spawn_on_thread<F, R>(fut: F) -> (JoinHandle<()>, ProcHandle<R>)
2021-11-14 17:50:59 +01:00
where
F: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
let (sender, receiver) = channel::unbounded();
2022-05-05 15:50:44 +02:00
let future = async move { fut.await };
2021-11-14 17:50:59 +01:00
let schedule = move |t| sender.send(t).unwrap();
2022-05-05 15:50:44 +02:00
let (proc, handle) = LightProc::build(future, schedule);
2021-11-14 17:50:59 +01:00
proc.schedule();
let join = thread::spawn(move || {
2021-11-14 17:50:59 +01:00
for proc in receiver {
println!("Got a task: {:?}", proc);
2021-11-14 17:50:59 +01:00
proc.run();
}
});
(join, handle)
2021-11-14 17:50:59 +01:00
}
fn main() {
let (join, handle) = spawn_on_thread(async {
2021-11-14 17:50:59 +01:00
println!("Sleeping!");
async_std::task::sleep(Duration::from_millis(100)).await;
println!("Done sleeping 1");
async_std::task::sleep(Duration::from_millis(100)).await;
println!("Done sleeping 2");
async_std::task::sleep(Duration::from_millis(100)).await;
println!("Done sleeping 3");
async_std::task::sleep(Duration::from_millis(100)).await;
println!("Done sleeping 4");
return 32;
});
let output = executor::block_on(handle);
assert_eq!(output, Some(32));
assert!(join.join().is_ok());
2021-11-14 17:50:59 +01:00
}