pub trait DistributedLock: Send + Sync {
type Handle: LockHandle + Send;
// Required methods
fn name(&self) -> &str;
fn acquire(
&self,
timeout: Option<Duration>,
) -> impl Future<Output = LockResult<Self::Handle>> + Send;
fn try_acquire(
&self,
) -> impl Future<Output = LockResult<Option<Self::Handle>>> + 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 = LockResult<Self::Handle>> + Send
fn acquire( &self, timeout: Option<Duration>, ) -> impl Future<Output = LockResult<Self::Handle>> + 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.
Sourcefn try_acquire(
&self,
) -> impl Future<Output = LockResult<Option<Self::Handle>>> + Send
fn try_acquire( &self, ) -> impl Future<Output = LockResult<Option<Self::Handle>>> + Send
Attempts to acquire the lock without waiting.
§Returns
Ok(Some(handle))- Lock acquired successfullyOk(None)- Lock is held by another processErr(...)- Error occurred during attempt
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.