condvar.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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::{
  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 Future for CondVarWait<'_> {
  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 futures::{select, FutureExt};
  132. use smol::Executor;
  133. use std::sync::Arc;
  134. #[test]
  135. fn condvar_test() {
  136. let executor = Arc::new(Executor::new());
  137. let executor_ = executor.clone();
  138. smol::block_on(executor.run(async move {
  139. let cv = Arc::new(CondVar::new());
  140. let cv_ = cv.clone();
  141. executor_
  142. .spawn(async move {
  143. // Waits here until notify() is called
  144. cv_.wait().await;
  145. })
  146. .detach();
  147. // Allow above code to continue
  148. cv.notify();
  149. }))
  150. }
  151. #[test]
  152. fn condvar_reset() {
  153. let executor = Arc::new(Executor::new());
  154. let executor_ = executor.clone();
  155. smol::block_on(executor.run(async move {
  156. let cv = Arc::new(CondVar::new());
  157. let cv_ = cv.clone();
  158. executor_
  159. .spawn(async move {
  160. cv_.wait().await;
  161. })
  162. .detach();
  163. // #1 send signal
  164. cv.notify();
  165. // Multiple calls to notify do nothing until we call reset()
  166. cv.notify();
  167. // Without calling reset(), then the wait() will return instantly
  168. cv.reset();
  169. let cv_ = cv.clone();
  170. executor_
  171. .spawn(async move {
  172. cv_.wait().await;
  173. })
  174. .detach();
  175. // #2 send signal again
  176. cv.notify();
  177. }))
  178. }
  179. #[test]
  180. fn condvar_double_wait() {
  181. let executor = Arc::new(Executor::new());
  182. let executor_ = executor.clone();
  183. smol::block_on(executor.run(async move {
  184. let cv = Arc::new(CondVar::new());
  185. let cv2 = cv.clone();
  186. let cv3 = cv.clone();
  187. executor_.spawn(async move { cv2.wait().await }).detach();
  188. executor_.spawn(async move { cv3.wait().await }).detach();
  189. // Allow above code to continue
  190. cv.notify();
  191. }))
  192. }
  193. #[test]
  194. fn condvar_wait_after_notify() {
  195. let executor = Arc::new(Executor::new());
  196. let executor_ = executor.clone();
  197. smol::block_on(executor.run(async move {
  198. let cv = Arc::new(CondVar::new());
  199. let cv2 = cv.clone();
  200. executor_.spawn(async move { cv2.wait().await }).detach();
  201. cv.notify();
  202. // Should complete immediately
  203. let cv2 = cv.clone();
  204. executor_.spawn(async move { cv2.wait().await }).detach();
  205. }))
  206. }
  207. #[test]
  208. fn condvar_drop() {
  209. let executor = Arc::new(Executor::new());
  210. let executor_ = executor.clone();
  211. smol::block_on(executor.run(async move {
  212. let cv = Arc::new(CondVar::new());
  213. let cv_ = cv.clone();
  214. executor_
  215. .spawn(async move {
  216. select! {
  217. () = cv_.wait().fuse() => (),
  218. () = (async {}).fuse() => ()
  219. }
  220. // The above future was dropped and we make a new one
  221. cv_.wait().await
  222. })
  223. .detach();
  224. // Allow above code to continue
  225. cv.notify();
  226. }))
  227. }
  228. }