From d1c816660c0583db33d160e2ef3e980bef0d5a85 Mon Sep 17 00:00:00 2001 From: hozan23 Date: Mon, 27 May 2024 00:59:23 +0200 Subject: p2p: WIP rpc server implementation for the p2p monitor --- p2p/examples/monitor/src/shared.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 p2p/examples/monitor/src/shared.rs (limited to 'p2p/examples/monitor/src/shared.rs') diff --git a/p2p/examples/monitor/src/shared.rs b/p2p/examples/monitor/src/shared.rs new file mode 100644 index 0000000..0e8079c --- /dev/null +++ b/p2p/examples/monitor/src/shared.rs @@ -0,0 +1,31 @@ +use std::{num::NonZeroUsize, sync::Arc, thread}; + +use easy_parallel::Parallel; +use smol::{channel, future, future::Future, Executor}; + +/// Returns an estimate of the default amount of parallelism a program should use. +/// see `std::thread::available_parallelism` +pub fn available_parallelism() -> usize { + thread::available_parallelism() + .map(NonZeroUsize::get) + .unwrap_or(1) +} + +/// Run a multi-threaded executor +pub fn run_executor(main_future: impl Future, ex: Arc>) { + let (signal, shutdown) = channel::unbounded::<()>(); + + let num_threads = available_parallelism(); + + Parallel::new() + .each(0..(num_threads), |_| { + future::block_on(ex.run(shutdown.recv())) + }) + // Run the main future on the current thread. + .finish(|| { + future::block_on(async { + main_future.await; + drop(signal); + }) + }); +} -- cgit v1.2.3