condvar.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{
  19. future::Future,
  20. pin::Pin,
  21. sync::Mutex,
  22. task::{Context, Poll, Waker},
  23. };
  24. /// Condition variables allow you to block a task while waiting for an event to occur.
  25. /// Condition variables are typically associated with a boolean predicate (a condition).
  26. /// ```rust
  27. /// let cv = Arc::new(CondVar::new());
  28. ///
  29. /// let cv_ = cv.clone();
  30. /// executor_
  31. /// .spawn(async move {
  32. /// // Waits here until notify() is called
  33. /// cv_.wait().await;
  34. /// // Check for some condition...
  35. /// })
  36. /// .detach();
  37. ///
  38. /// // Allow above code to continue
  39. /// cv.notify();
  40. /// ```
  41. /// After the condition variable is woken up, the user may `wait` again for another `notify`
  42. /// signal by first calling `cv_.reset()`.
  43. pub struct CondVar {
  44. state: Mutex<CondVarState>,
  45. }
  46. struct CondVarState {
  47. is_awake: bool,
  48. waker: Option<Waker>,
  49. }
  50. impl CondVar {
  51. pub fn new() -> Self {
  52. Self { state: Mutex::new(CondVarState { is_awake: false, waker: None }) }
  53. }
  54. /// Wakeup the waiting task. Subsequent calls to this do nothing until `wait()` is called.
  55. pub fn notify(&self) {
  56. let mut state = self.state.lock().unwrap();
  57. state.is_awake = true;
  58. // Notify the executor that the pending future from wait() is to be polled again.
  59. if let Some(waker) = state.waker.take() {
  60. waker.wake()
  61. }
  62. }
  63. /// Reset the condition variable and wait for a notification
  64. pub fn wait(&self) -> CondVarWait {
  65. CondVarWait { state: &self.state }
  66. }
  67. /// Reset self ready to wait() again.
  68. /// The reason this is separate from `wait()` is that usually
  69. /// on the first `wait()` we want to catch any `notify()` calls that
  70. /// happened before we started. For example,
  71. /// ```rust
  72. /// loop {
  73. /// // Wait for signal
  74. /// cv.wait().await;
  75. ///
  76. /// // Do stuff...
  77. ///
  78. /// cv.reset();
  79. /// }
  80. /// ```
  81. pub fn reset(&self) {
  82. let mut state = self.state.lock().unwrap();
  83. state.is_awake = false;
  84. }
  85. }
  86. impl Default for CondVar {
  87. fn default() -> Self {
  88. Self::new()
  89. }
  90. }
  91. /// Awaitable futures object returned by `condvar.wait()`
  92. pub struct CondVarWait<'a> {
  93. state: &'a Mutex<CondVarState>,
  94. }
  95. impl<'a> Future for CondVarWait<'a> {
  96. type Output = ();
  97. fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  98. let mut state = self.state.lock().unwrap();
  99. // Avoid cloning wherever possible.
  100. // This code below is equivalent to:
  101. //
  102. // state.waker = Some(cx.waker().clone());
  103. //
  104. // However checking whether the waker we have wakes up the same task
  105. // as the one in the context cx, means we don't have to re-clone if
  106. // we already have it.
  107. //
  108. // It's a minor thing which is basically recommended in the docs on
  109. // creating pollable futures.
  110. let new_waker = match state.waker.take() {
  111. Some(waker) => {
  112. let cx_waker = cx.waker();
  113. if cx_waker.will_wake(&waker) {
  114. waker
  115. } else {
  116. cx_waker.clone()
  117. }
  118. }
  119. None => cx.waker().clone(),
  120. };
  121. state.waker = Some(new_waker);
  122. match state.is_awake {
  123. true => Poll::Ready(()),
  124. false => Poll::Pending,
  125. }
  126. }
  127. }
  128. #[cfg(test)]
  129. mod tests {
  130. use super::*;
  131. use smol::Executor;
  132. use std::sync::Arc;
  133. #[test]
  134. fn condvar_test() {
  135. let executor = Arc::new(Executor::new());
  136. let executor_ = executor.clone();
  137. smol::block_on(executor.run(async move {
  138. let cv = Arc::new(CondVar::new());
  139. let cv_ = cv.clone();
  140. executor_
  141. .spawn(async move {
  142. // Waits here until notify() is called
  143. cv_.wait().await;
  144. })
  145. .detach();
  146. // Allow above code to continue
  147. cv.notify();
  148. }))
  149. }
  150. #[test]
  151. fn condvar_reset() {
  152. let executor = Arc::new(Executor::new());
  153. let executor_ = executor.clone();
  154. smol::block_on(executor.run(async move {
  155. let cv = Arc::new(CondVar::new());
  156. let cv_ = cv.clone();
  157. executor_
  158. .spawn(async move {
  159. cv_.wait().await;
  160. })
  161. .detach();
  162. // #1 send signal
  163. cv.notify();
  164. // Multiple calls to notify do nothing until we call reset()
  165. cv.notify();
  166. // Without calling reset(), then the wait() will return instantly
  167. cv.reset();
  168. let cv_ = cv.clone();
  169. executor_
  170. .spawn(async move {
  171. cv_.wait().await;
  172. })
  173. .detach();
  174. // #2 send signal again
  175. cv.notify();
  176. }))
  177. }
  178. }