pub async fn lock_across<C, F>(
connections: &[Arc<Mutex<C>>],
resource: &str,
f: F,
options: LockAcrossOptions,
) -> Result<F::Output, LockAcrossError>Expand description
Executes a function while locking on a single resource using the RedLock algorithm.
This is much more efficient than crate::MultiResourceLock when you only need to lock a single
resource. Ideally you should architect your application so you never need crate::MultiResourceLock.
connectionsis used to acquire mutable references on connections to acquire the lock and then used to acquire mutable references on connections to release the lock.resourceis the name of the resource to lock.optionsthe options to configure acquisition.
// Get connection.
let connection = Arc::new(Mutex::new(client.get_multiplexed_async_connection().await?));
// Set state.
let x: usize = 0;
let ptr = &mut x as *mut usize as usize;
// Execute racy functions with lock.
const N: usize = 100_000;
let futures = (0..N).map(|_|{
let cconnection = connection.clone();
task::spawn(async move {
lock_across(
&[cconnection],
"resource",
async move {
unsafe { *(ptr as *mut usize) += 1 };
},
LockAcrossOptions::default(),
);
})
}).collect::<Vec<_>>();
for future in futures {
future.await?;
}
// Assert state.
assert_eq!(x, N);