pub fn spawn_lock_manager(etcd: Client) -> (LockManagerHandle, LockManager)Expand description
Creates a lock manager to create “managed” locks.
Managed lock’s lifecycle is managed by the lock manager background thread, that includes: - Automatic lease refresh - Lock revocation when the lock is dropped
You can clone [LockManager] to share it across threads, it is really cheap to do so.
The lock manager background thread will stop when all the [LockManager] is dropped.
You can await on the [LockManagerHandle] to wait for the lock manager background thread to stop.
Dropping the [LockManagerHandle] will not stop the lock manager background thread, but it is not recommended to do so
as you are suppoed to await the handle to gracefully shutdown.
Examples
use etcd_client::Client;
use rust_etcd_utils::{lock::spawn_lock_manager, ManagedLock};
let etcd = Client::connect(["http://localhost:2379"], None).await.expect("failed to connect to etcd");
let (lock_man_handle, lock_man) = spawn_lock_manager(etcd.clone());
// Do something with the lock manager
let managed_lock: ManagedLock = lock_man.try_lock("test").await.expect("failed to lock");
drop(lock_man);
// Wait for the lock manager background thread to stop
lock_man_handle.await.expect("failed to release lock manager handle");Cloning the lock manager is cheap and can be shared across threads.
use etcd_client::Client;
use rust_etcd_utils::{lock::spawn_lock_manager, lock::ManagedLock, lock::TryLockError};
let etcd = Client::connect(["http://localhost:2379"], None).await.expect("failed to connect to etcd");
let (_, lock_man) = spawn_lock_manager(etcd.clone());
let lock_man2 = lock_man.clone();
let task1 = tokio::spawn(async move {
let managed_lock: ManagedLock = lock_man2.try_lock("test").await.expect("failed to lock");
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
});
let err = lock_man.try_lock("test").await;
assert!(matches!(err, Err(TryLockError::AlreadyTaken)));