Skip to content

Commit c2849af

Browse files
fbqIngo Molnar
authored andcommitted
rust: sync: lock: Add an example for Guard:: Lock_ref()
To provide examples on usage of `Guard::lock_ref()` along with the unit test, an "assert a lock is held by a guard" example is added. (Also apply feedback from Benno.) Signed-off-by: Boqun Feng <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Link: https://lore.kernel.org/r/[email protected] Link: https://lore.kernel.org/r/[email protected]
1 parent 8f65291 commit c2849af

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

rust/kernel/sync/lock.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,30 @@ unsafe impl<T: Sync + ?Sized, B: Backend> Sync for Guard<'_, T, B> {}
201201

202202
impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
203203
/// Returns the lock that this guard originates from.
204+
///
205+
/// # Examples
206+
///
207+
/// The following example shows how to use [`Guard::lock_ref()`] to assert the corresponding
208+
/// lock is held.
209+
///
210+
/// ```
211+
/// # use kernel::{new_spinlock, stack_pin_init, sync::lock::{Backend, Guard, Lock}};
212+
///
213+
/// fn assert_held<T, B: Backend>(guard: &Guard<'_, T, B>, lock: &Lock<T, B>) {
214+
/// // Address-equal means the same lock.
215+
/// assert!(core::ptr::eq(guard.lock_ref(), lock));
216+
/// }
217+
///
218+
/// // Creates a new lock on the stack.
219+
/// stack_pin_init!{
220+
/// let l = new_spinlock!(42)
221+
/// }
222+
///
223+
/// let g = l.lock();
224+
///
225+
/// // `g` originates from `l`.
226+
/// assert_held(&g, &l);
227+
/// ```
204228
pub fn lock_ref(&self) -> &'a Lock<T, B> {
205229
self.lock
206230
}

0 commit comments

Comments
 (0)