Skip to content

Lock Guard Drop for tokio-comp #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
theBeardA opened this issue Mar 7, 2025 · 1 comment
Open

Lock Guard Drop for tokio-comp #30

theBeardA opened this issue Mar 7, 2025 · 1 comment

Comments

@theBeardA
Copy link
Contributor

I was implementing my own lock manager when i came across this library. since my code base is based on tokio and I dont want to bring in async-std, I was wondering if Drop implementation for the tokio-comp feature using conditional compile is the way to go? I might be missing something, but from my initial experiments, this approach appears to work for Drop.​

#[cfg(feature = "tokio-comp")]
impl Drop for LockGuard {
    fn drop(&mut self) {
        let lock = self.lock.clone();
        let lock_manager = self.lock.lock_manager.clone();
        tokio::spawn(async move {
            let _ = lock_manager.unlock(&lock).await;
        });
    }
}
@theBeardA theBeardA changed the title Lock Guard Drop for tokio Lock Guard Drop for tokio-comp Mar 7, 2025
@hexcowboy
Copy link
Owner

rslock >0.7.0 intends for you to explicitly handle drop by calling unlock. Doing otherwise could lead to race conditions.

let lock = lock_manager.lock(key, ttl).await?;
// do work
lock_manager.unlock(&lock).await; // Explicit unlock

See

rslock/src/lock.rs

Lines 397 to 407 in d84f38f

pub async fn unlock(&self, lock: &Lock) {
let l = self.lock_inner().await;
let mut servers = l.servers.clone();
drop(l);
join_all(
servers
.iter_mut()
.map(|client| client.unlock(&lock.resource, &lock.val)),
)
.await;
}

If you really want to implement manual dropping without unlock(), you could do something like this

pub struct AutoUnlockGuard {
    lock: Lock,
    released: bool,
}

impl AutoUnlockGuard {
    pub fn new(lock: Lock) -> Self {
        Self {
            lock,
            released: false,
        }
    }

    pub async fn release(&mut self) {
        if !self.released {
            self.released = true;
            self.lock.lock_manager.unlock(&self.lock).await;
        }
    }
}

impl Drop for AutoUnlockGuard {
    fn drop(&mut self) {
        if !self.released {
            log::warn!("AutoUnlockGuard dropped without explicit release");
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants