mod.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. pub type ExecutorPtr = Arc<Executor<'static>>;
  34. /// Sleep for any number of seconds.
  35. pub async fn sleep(seconds: u64) {
  36. Timer::after(Duration::from_secs(seconds)).await;
  37. }
  38. pub async fn sleep_forever() {
  39. loop {
  40. sleep(100000000).await
  41. }
  42. }
  43. /// Sleep for any number of milliseconds.
  44. pub async fn msleep(millis: u64) {
  45. Timer::after(Duration::from_millis(millis)).await;
  46. }
  47. /// Run a task until it has fully completed, irrespective of whether the parent task still exists.
  48. pub async fn run_until_completion<'a, R: Send + 'a, F: Future<Output = R> + Send + 'a>(
  49. func: F,
  50. executor: Arc<Executor<'a>>,
  51. ) -> R {
  52. let (sender, recv_queue) = smol::channel::bounded::<R>(1);
  53. executor
  54. .spawn(async move {
  55. let result = func.await;
  56. // We ignore this result: an error would mean the parent task has been cancelled,
  57. // which is valid behavior.
  58. let _ = sender.send(result).await;
  59. })
  60. .detach();
  61. // This should never panic because it would mean the detached task has not completed.
  62. recv_queue.recv().await.expect("Run until completion task failed")
  63. }