pub struct NoWaitLock<T: ?Sized> { /* private fields */ }
Expand description

A lock that only offers a try_lock method.

That is, on contention it doesn’t offer a way for the caller to block waiting for the current owner to release the lock. This is useful for best-effort kind of scenarios where waiting is never needed: in such cases, users don’t need a full-featured mutex or spinlock.

When the lock is released via call to NoWaitLockGuard::unlock, it indicates to the caller whether there was contention (i.e., if another thread tried and failed to acquire this lock). If the return value is false, there was definitely no contention but if it is true, it’s possible that the contention was when attempting to acquire the lock.

Examples

use kernel::sync::NoWaitLock;

#[derive(PartialEq)]
struct Example {
    a: u32,
    b: u32,
}

let x = NoWaitLock::new(Example { a: 10, b: 20 });

// Modifying the protected value.
{
    let mut guard = x.try_lock().unwrap();
    assert_eq!(guard.a, 10);
    assert_eq!(guard.b, 20);
    guard.a += 20;
    guard.b += 20;
    assert_eq!(guard.a, 30);
    assert_eq!(guard.b, 40);
}

// Reading the protected value.
{
    let guard = x.try_lock().unwrap();
    assert_eq!(guard.a, 30);
    assert_eq!(guard.b, 40);
}

// Second acquire fails, but succeeds after the guard is dropped.
{
    let guard = x.try_lock().unwrap();
    assert!(x.try_lock().is_none());

    drop(guard);
    assert!(x.try_lock().is_some());
}

The following examples use the NoWaitLockGuard::unlock to release the lock and check for contention.

use kernel::sync::NoWaitLock;

#[derive(PartialEq)]
struct Example {
    a: u32,
    b: u32,
}

let x = NoWaitLock::new(Example { a: 10, b: 20 });

// No contention when lock is released.
let guard = x.try_lock().unwrap();
assert_eq!(guard.unlock(), false);

// Contention detected.
let guard = x.try_lock().unwrap();
assert!(x.try_lock().is_none());
assert_eq!(guard.unlock(), true);

// No contention again.
let guard = x.try_lock().unwrap();
assert_eq!(guard.a, 10);
assert_eq!(guard.b, 20);
assert_eq!(guard.unlock(), false);

Implementations

Creates a new instance of the no-wait lock.

Tries to acquire the lock.

If no other thread/CPU currently owns the lock, it returns a guard that can be used to access the protected data. Otherwise (i.e., the lock is already owned), it returns None.

Trait Implementations

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

This documentation is an old archive. Please see https://rust.docs.kernel.org instead.