Skip to content

A new lock: AbLock #6875

Answered by Darksonn
xuxiaocheng0201 asked this question in Ideas
Sep 28, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

I think something along these lines would work:

use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::Notify;

pub struct AbLock {
    /// Bit 0 determines the kind of lock.
    /// Remaining bits count the number of times the lock has been taken.
    state: AtomicUsize,
    notify: [Notify; 2],
}

impl AbLock {
    pub fn try_lock(&self, kind: bool) -> Option<AbLockGuard<'_>> {
        let kind = kind as usize;
        let mut prev_state = self.state.load(Ordering::Relaxed);
        loop {
            let is_empty = prev_state <= 1;
            let is_right_kind = (prev_state & 1) == kind;

            let new_state = if is_empty {
                // Set counter to one. Set lo…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@xuxiaocheng0201
Comment options

Answer selected by xuxiaocheng0201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
2 participants