rt.rs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. macro_rules! d { ($($arg:tt)*) => { debug!(target: "rt", $($arg)*); } }
  23. macro_rules! t { ($($arg:tt)*) => { trace!(target: "rt", $($arg)*); } }
  24. pub type ExecutorPtr = Arc<smol::Executor<'static>>;
  25. pub struct AsyncRuntime {
  26. name: &'static str,
  27. signal: Sender<()>,
  28. shutdown: Receiver<()>,
  29. exec_threadpool: SyncMutex<Vec<thread::JoinHandle<()>>>,
  30. ex: ExecutorPtr,
  31. tasks: SyncMutex<Vec<Task<()>>>,
  32. }
  33. impl AsyncRuntime {
  34. pub fn new(ex: ExecutorPtr, name: &'static str) -> Self {
  35. let (signal, shutdown) = async_channel::unbounded::<()>();
  36. Self {
  37. name,
  38. signal,
  39. shutdown,
  40. exec_threadpool: SyncMutex::new(vec![]),
  41. ex,
  42. tasks: SyncMutex::new(vec![]),
  43. }
  44. }
  45. pub fn start(&self) {
  46. let n_threads = thread::available_parallelism().unwrap().get();
  47. self.start_with_count(n_threads);
  48. }
  49. pub fn start_with_count(&self, n_threads: usize) {
  50. let mut exec_threadpool = Vec::with_capacity(n_threads);
  51. // N executor threads
  52. for _ in 0..n_threads {
  53. let shutdown = self.shutdown.clone();
  54. let ex = self.ex.clone();
  55. let handle = thread::spawn(move || {
  56. let _ = smol::future::block_on(ex.run(shutdown.recv()));
  57. });
  58. exec_threadpool.push(handle);
  59. }
  60. *self.exec_threadpool.lock() = exec_threadpool;
  61. info!(target: "rt", "[{}] Started runtime [{n_threads} threads]", self.name);
  62. }
  63. pub fn push_task(&self, task: Task<()>) {
  64. self.tasks.lock().push(task);
  65. }
  66. pub fn stop(&self) {
  67. let exec_threadpool = std::mem::take(&mut *self.exec_threadpool.lock());
  68. d!("[{}] Stopping async runtime...", self.name);
  69. // Just drop all the tasks without waiting for them to finish.
  70. self.tasks.lock().clear();
  71. for _ in &exec_threadpool {
  72. self.signal.try_send(()).unwrap();
  73. }
  74. for handle in exec_threadpool {
  75. handle.join().unwrap();
  76. }
  77. t!("[{}] Stopped runtime", self.name);
  78. }
  79. }