|
| 1 | +use crate::rcl_bindings::*; |
| 2 | +use crate::{Context, RclrsError, ToResult}; |
| 3 | + |
| 4 | +use std::sync::{atomic::AtomicBool, Arc, Mutex}; |
| 5 | + |
| 6 | +/// A waitable entity used for waking up a wait set manually. |
| 7 | +/// |
| 8 | +/// If a wait set that is currently waiting on events should be interrupted from a separate thread, this can be done |
| 9 | +/// by adding an `Arc<GuardCondition>` to the wait set, and calling `trigger()` on the same `GuardCondition` while |
| 10 | +/// the wait set is waiting. |
| 11 | +/// |
| 12 | +/// The guard condition may be reused multiple times, but like other waitable entities, can not be used in |
| 13 | +/// multiple wait sets concurrently. |
| 14 | +/// |
| 15 | +/// # Example |
| 16 | +/// ``` |
| 17 | +/// # use rclrs::{Context, GuardCondition, WaitSet, RclrsError}; |
| 18 | +/// # use std::sync::{Arc, atomic::Ordering}; |
| 19 | +/// |
| 20 | +/// let context = Context::new([])?; |
| 21 | +/// |
| 22 | +/// let atomic_bool = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 23 | +/// let atomic_bool_for_closure = Arc::clone(&atomic_bool); |
| 24 | +/// |
| 25 | +/// let gc = Arc::new(GuardCondition::new( |
| 26 | +/// &context, |
| 27 | +/// Some(Box::new(move || { |
| 28 | +/// atomic_bool_for_closure.store(true, Ordering::Relaxed); |
| 29 | +/// })), |
| 30 | +/// )); |
| 31 | +/// |
| 32 | +/// let mut ws = WaitSet::new(0, 1, 0, 0, 0, 0, &context)?; |
| 33 | +/// ws.add_guard_condition(Arc::clone(&gc))?; |
| 34 | +/// |
| 35 | +/// // Trigger the guard condition, firing the callback and waking the wait set being waited on, if any. |
| 36 | +/// gc.trigger()?; |
| 37 | +/// |
| 38 | +/// // The provided callback has now been called. |
| 39 | +/// assert_eq!(atomic_bool.load(Ordering::Relaxed), true); |
| 40 | +/// |
| 41 | +/// // The wait call will now immediately return. |
| 42 | +/// ws.wait(Some(std::time::Duration::from_millis(10)))?; |
| 43 | +/// |
| 44 | +/// # Ok::<(), RclrsError>(()) |
| 45 | +/// ``` |
| 46 | +pub struct GuardCondition { |
| 47 | + /// The rcl_guard_condition_t that this struct encapsulates. |
| 48 | + pub(crate) rcl_guard_condition: Arc<Mutex<rcl_guard_condition_t>>, |
| 49 | + /// An optional callback to call when this guard condition is triggered. |
| 50 | + callback: Option<Box<dyn Fn() + Send + Sync>>, |
| 51 | + /// A flag to indicate if this guard condition has already been assigned to a wait set. |
| 52 | + pub(crate) in_use_by_wait_set: Arc<AtomicBool>, |
| 53 | +} |
| 54 | + |
| 55 | +impl Drop for GuardCondition { |
| 56 | + fn drop(&mut self) { |
| 57 | + unsafe { |
| 58 | + // SAFETY: No precondition for this function (besides passing in a valid guard condition) |
| 59 | + rcl_guard_condition_fini(&mut *self.rcl_guard_condition.lock().unwrap()); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl PartialEq for GuardCondition { |
| 65 | + fn eq(&self, other: &Self) -> bool { |
| 66 | + // Because GuardCondition controls the creation of the rcl_guard_condition, each unique GuardCondition should have a unique |
| 67 | + // rcl_guard_condition. Thus comparing equality of this member should be enough. |
| 68 | + Arc::ptr_eq(&self.rcl_guard_condition, &other.rcl_guard_condition) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl Eq for GuardCondition {} |
| 73 | + |
| 74 | +// SAFETY: rcl_guard_condition is the only member that doesn't implement Send, and it is designed to be accessed from other threads |
| 75 | +unsafe impl Send for rcl_guard_condition_t {} |
| 76 | + |
| 77 | +// SAFETY: The mutexes and atomic members ensure synchronized access to members, and the callback is reentrant |
| 78 | +unsafe impl Sync for GuardCondition {} |
| 79 | + |
| 80 | +impl GuardCondition { |
| 81 | + /// Creates a new guard condition. |
| 82 | + pub fn new(context: &Context, callback: Option<Box<dyn Fn() + Send + Sync>>) -> Arc<Self> { |
| 83 | + // SAFETY: Getting a zero initialized value is always safe |
| 84 | + let mut guard_condition = unsafe { rcl_get_zero_initialized_guard_condition() }; |
| 85 | + unsafe { |
| 86 | + // SAFETY: The context must be valid, and the guard condition must be zero-initialized |
| 87 | + rcl_guard_condition_init( |
| 88 | + &mut guard_condition, |
| 89 | + &mut *context.rcl_context_mtx.lock().unwrap(), |
| 90 | + rcl_guard_condition_get_default_options(), |
| 91 | + ); |
| 92 | + } |
| 93 | + |
| 94 | + Arc::new(Self { |
| 95 | + rcl_guard_condition: Arc::new(Mutex::new(guard_condition)), |
| 96 | + callback, |
| 97 | + in_use_by_wait_set: Arc::new(AtomicBool::new(false)), |
| 98 | + }) |
| 99 | + } |
| 100 | + |
| 101 | + /// Triggers this guard condition, activating the wait set, and calling the optionally assigned callback. |
| 102 | + pub fn trigger(&self) -> Result<(), RclrsError> { |
| 103 | + unsafe { |
| 104 | + // SAFETY: The rcl_guard_condition_t is valid. |
| 105 | + rcl_trigger_guard_condition(&mut *self.rcl_guard_condition.lock().unwrap()).ok()?; |
| 106 | + } |
| 107 | + if let Some(callback) = &self.callback { |
| 108 | + callback(); |
| 109 | + } |
| 110 | + Ok(()) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +#[cfg(test)] |
| 115 | +mod tests { |
| 116 | + use super::*; |
| 117 | + use crate::WaitSet; |
| 118 | + use std::sync::atomic::Ordering; |
| 119 | + |
| 120 | + #[test] |
| 121 | + fn test_guard_condition() -> Result<(), RclrsError> { |
| 122 | + let context = Context::new([])?; |
| 123 | + |
| 124 | + let atomic_bool = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 125 | + let atomic_bool_for_closure = Arc::clone(&atomic_bool); |
| 126 | + |
| 127 | + let guard_condition = GuardCondition::new( |
| 128 | + &context, |
| 129 | + Some(Box::new(move || { |
| 130 | + atomic_bool_for_closure.store(true, Ordering::Relaxed); |
| 131 | + })), |
| 132 | + ); |
| 133 | + |
| 134 | + guard_condition.trigger()?; |
| 135 | + |
| 136 | + assert!(atomic_bool.load(Ordering::Relaxed)); |
| 137 | + |
| 138 | + Ok(()) |
| 139 | + } |
| 140 | + |
| 141 | + #[test] |
| 142 | + fn test_guard_condition_wait() -> Result<(), RclrsError> { |
| 143 | + let context = Context::new([])?; |
| 144 | + |
| 145 | + let atomic_bool = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 146 | + let atomic_bool_for_closure = Arc::clone(&atomic_bool); |
| 147 | + |
| 148 | + let guard_condition = GuardCondition::new( |
| 149 | + &context, |
| 150 | + Some(Box::new(move || { |
| 151 | + atomic_bool_for_closure.store(true, Ordering::Relaxed); |
| 152 | + })), |
| 153 | + ); |
| 154 | + |
| 155 | + let mut wait_set = WaitSet::new(0, 1, 0, 0, 0, 0, &context)?; |
| 156 | + wait_set.add_guard_condition(Arc::clone(&guard_condition))?; |
| 157 | + guard_condition.trigger()?; |
| 158 | + |
| 159 | + assert!(atomic_bool.load(Ordering::Relaxed)); |
| 160 | + wait_set.wait(Some(std::time::Duration::from_millis(10)))?; |
| 161 | + |
| 162 | + Ok(()) |
| 163 | + } |
| 164 | + |
| 165 | + fn assert_send<T: Send>() {} |
| 166 | + fn assert_sync<T: Sync>() {} |
| 167 | + |
| 168 | + #[test] |
| 169 | + fn test_guard_condition_is_send_and_sync() { |
| 170 | + assert_send::<GuardCondition>(); |
| 171 | + assert_sync::<GuardCondition>(); |
| 172 | + } |
| 173 | +} |
0 commit comments