mod.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 std::{sync::Arc, time::Duration};
  19. use smol::{future::Future, Executor, Timer};
  20. /// Condition variable which allows a task to block until woken up
  21. pub mod condvar;
  22. pub use condvar::CondVar;
  23. /// Implementation of async background task spawning which are stoppable
  24. /// using channel signalling.
  25. pub mod stoppable_task;
  26. pub use stoppable_task::{StoppableTask, StoppableTaskPtr};
  27. /// Simple broadcast (publish-subscribe) class
  28. pub mod publisher;
  29. pub use publisher::{Publisher, PublisherPtr, Subscription};
  30. /// Async timeout implementations
  31. pub mod timeout;
  32. pub use timeout::io_timeout;
  33. /// Thread priority setting
  34. pub mod thread_priority;
  35. pub type ExecutorPtr = Arc<Executor<'static>>;
  36. /// Sleep for any number of seconds.
  37. pub async fn sleep(seconds: u64) {
  38. Timer::after(Duration::from_secs(seconds)).await;
  39. }
  40. pub async fn sleep_forever() {
  41. loop {
  42. sleep(100000000).await
  43. }
  44. }
  45. /// Sleep for any number of milliseconds.
  46. pub async fn msleep(millis: u64) {
  47. Timer::after(Duration::from_millis(millis)).await;
  48. }
  49. /// Run a task until it has fully completed, irrespective of whether the parent task still exists.
  50. pub async fn run_until_completion<'a, R: Send + 'a, F: Future<Output = R> + Send + 'a>(
  51. func: F,
  52. executor: Arc<Executor<'a>>,
  53. ) -> R {
  54. let (sender, recv_queue) = smol::channel::bounded::<R>(1);
  55. executor
  56. .spawn(async move {
  57. let result = func.await;
  58. // We ignore this result: an error would mean the parent task has been cancelled,
  59. // which is valid behavior.
  60. let _ = sender.send(result).await;
  61. })
  62. .detach();
  63. // This should never panic because it would mean the detached task has not completed.
  64. recv_queue.recv().await.expect("Run until completion task failed")
  65. }