[][src]Crate padlock

Aquire Mutex and RwLocks safely.

All methods in this crate will try to lock the passed Mutex or RwLock, if the locking fails, spin_loop_hint is called and we try again. This practice is called spinlock.

This means that all calls will block the current thread.

Important: When using methods like mutex_lock, remember that the lock is droped first when the lambda finishes running.

Example:

 use std::{
     thread,
     sync::{Arc, Mutex},
     time::Duration
 };

 #[derive(Debug)]
 struct Person {
     age: u8,
     name: String
 }

 fn main() {

     let people = Arc::new(Mutex::new(Vec::<Person>::new()));
     let mut threads = Vec::<thread::JoinHandle<()>>::new();

     // Write in one thread
     let people_clone = Arc::clone(&people);
     threads.push(thread::spawn(move || {

         for i in 0..10 {

             padlock::mutex_lock(&people_clone, |lock| {

                 lock.push(Person {
                     age: i * 10,
                     name: format!("Name {}", i)
                 });

             });

             thread::sleep(Duration::from_millis(500));

         }

     }));

     // Read from another
     let people_clone = Arc::clone(&people);
     threads.push(thread::spawn(move || {

         for _ in 0..6 {

             padlock::mutex_lock(&people_clone, |lock| {

                 for person in lock {
                     println!("{:?}", person);
                 }

             });

             thread::sleep(Duration::from_secs(1));

         }

     }));

     for t in threads {
         t.join();
     }

 }

Functions

get_mutex_lock

Get the MutexGuard directly, aquired with a spinlock.

get_rw_read_lock

Get the RwLockReadGuard directly, aquired with a spinlock.

get_rw_write_lock

Get the RwLockWriteGuard directly, aquired with a spinlock.

mutex_lock

Aquire a Mutex lock, passing the lock to the lambda. The lock is released when the lambda finishes. This function returns whatever the lambda returns, allowing you to extract data from a lock without having to worry about releasing the lock.

rw_read_lock

Aquire a RwLock read lock, passing the lock to the lambda. The lock is released when the lambda finishes. This function returns whatever the lambda returns, allowing you to extract data from a lock without having to worry about releasing the lock.

rw_write_lock

Aquire a RwLock write lock, passing the lock to the lambda. The lock is released when the lambda finishes. This function returns whatever the lambda returns, allowing you to extract data from a lock without having to worry about releasing the lock.