rt.rs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_channel::{Receiver, Sender};
  19. use parking_lot::Mutex as SyncMutex;
  20. use smol::Task;
  21. use std::{sync::Arc, thread};
  22. use crate::util::spawn_thread;
  23. macro_rules! d { ($($arg:tt)*) => { debug!(target: "rt", $($arg)*); } }
  24. macro_rules! t { ($($arg:tt)*) => { trace!(target: "rt", $($arg)*); } }
  25. pub type ExecutorPtr = Arc<smol::Executor<'static>>;
  26. pub struct AsyncRuntime {
  27. name: &'static str,
  28. signal: Sender<()>,
  29. shutdown: Receiver<()>,
  30. exec_threadpool: SyncMutex<Vec<thread::JoinHandle<()>>>,
  31. ex: ExecutorPtr,
  32. tasks: SyncMutex<Vec<Task<()>>>,
  33. }
  34. impl AsyncRuntime {
  35. pub fn new(ex: ExecutorPtr, name: &'static str) -> Self {
  36. let (signal, shutdown) = async_channel::unbounded::<()>();
  37. Self {
  38. name,
  39. signal,
  40. shutdown,
  41. exec_threadpool: SyncMutex::new(vec![]),
  42. ex,
  43. tasks: SyncMutex::new(vec![]),
  44. }
  45. }
  46. pub fn start(&self) {
  47. let n_threads = thread::available_parallelism().unwrap().get();
  48. self.start_with_count(n_threads);
  49. }
  50. pub fn start_with_count(&self, n_threads: usize) {
  51. let mut exec_threadpool = Vec::with_capacity(n_threads);
  52. // N executor threads
  53. for i in 0..n_threads {
  54. let shutdown = self.shutdown.clone();
  55. let ex = self.ex.clone();
  56. let name = format!("{}-{}", self.name, i);
  57. let handle = spawn_thread(name, move || {
  58. let _ = smol::future::block_on(ex.run(shutdown.recv()));
  59. });
  60. exec_threadpool.push(handle);
  61. }
  62. *self.exec_threadpool.lock() = exec_threadpool;
  63. info!(target: "rt", "[{}] Started runtime [{n_threads} threads]", self.name);
  64. }
  65. pub fn push_task(&self, task: Task<()>) {
  66. self.tasks.lock().push(task);
  67. }
  68. pub fn stop(&self) {
  69. let exec_threadpool = std::mem::take(&mut *self.exec_threadpool.lock());
  70. d!("[{}] Stopping async runtime...", self.name);
  71. // Just drop all the tasks without waiting for them to finish.
  72. self.tasks.lock().clear();
  73. for _ in &exec_threadpool {
  74. self.signal.try_send(()).unwrap();
  75. }
  76. for handle in exec_threadpool {
  77. handle.join().unwrap();
  78. }
  79. t!("[{}] Stopped runtime", self.name);
  80. }
  81. }