pub trait DistributedLock: Send + Sync {
type Handle: LockHandle + Send;
// Required methods
fn name(&self) -> &str;
fn acquire(
&self,
timeout: Option<Duration>,
) -> impl Future<Output = Result<Self::Handle, LockError>> + Send;
fn try_acquire(
&self,
) -> impl Future<Output = Result<Option<Self::Handle>, LockError>> + Send;
}Expand description
A distributed mutual exclusion lock.
Provides exclusive access to a resource identified by name across
processes and machines. The specific backend (PostgreSQL, Redis, file
system, etc.) determines how the lock is implemented.
§Example
ⓘ
use distributed_lock_core::DistributedLock;
async fn protected_operation(lock: &impl DistributedLock) -> Result<(), Error> {
// Acquire with 5 second timeout
let handle = lock.acquire(Some(Duration::from_secs(5))).await?;
// We have exclusive access
perform_critical_section().await?;
// Release (also happens on drop)
handle.release().await?;
Ok(())
}Required Associated Types§
Sourcetype Handle: LockHandle + Send
type Handle: LockHandle + Send
The handle type returned when the lock is acquired.
Required Methods§
Sourcefn acquire(
&self,
timeout: Option<Duration>,
) -> impl Future<Output = Result<Self::Handle, LockError>> + Send
fn acquire( &self, timeout: Option<Duration>, ) -> impl Future<Output = Result<Self::Handle, LockError>> + Send
Acquires the lock, waiting up to timeout.
§Arguments
timeout- Maximum time to wait.Nonemeans wait indefinitely.
§Returns
Ok(handle)- Lock acquired successfullyErr(LockError::Timeout)- Timeout expired before lock acquiredErr(LockError::Cancelled)- Operation was cancelledErr(LockError::Connection)- Backend connection failed
§Cancellation
This operation can be cancelled by dropping the returned future or using
tokio::select! with a cancellation branch. Backends should check for
cancellation periodically during the wait.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.