ReentrantLock

Struct ReentrantLock 

Source
pub struct ReentrantLock { /* private fields */ }
Expand description

ReentrantLock implemented using Semaphore(1).

This Lock does not need to be mutable on calling, it is safe to share across multiple threads even with read only mode.

Example:

use std::sync::Arc;
use std::time::Duration;
use std::thread;
use classic_sync::lock::ReentrantLock;
let lock = ReentrantLock::new();
let arc_lock = Arc::new(lock);
for i in 0..3 {
    let lock_copy = Arc::clone(&arc_lock);
    let tid = i;
    thread::spawn(move || {
        lock_copy.lock();
        println!("Now we are in critical section!");
        std::thread::sleep(Duration::from_secs(3));
        // Other people can't acquire the lock even when I am sleeping.
        lock_copy.unlock(); // You have to manually unlock it to release the lock
    });
}

Implementations§

Source§

impl ReentrantLock

Implementation of ReentrantLock

Source

pub fn new() -> ReentrantLock

Create a new Lock object. Lock can be shared using Arc with readonly access

Source

pub fn lock(&self)

Acquire the lock and wait indefinitely for it to happen Calling on already locked lock will block forever (dead lock) It is calling internal semaphore’s p() operation effectively.

Source

pub fn unlock(&self)

Release the lock. Do not call unlock multiple times. It will give non-exclusive access any more! It is calling internal semaphore’s v() operation effectively.

Source

pub fn try_lock(&self, timeout: Duration) -> bool

Try to acquire a lock. Return true if lock is acquired. Return false if acquire timed out.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.