1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Definition and implementations of `LockFreeStack`
//!
use hazard_epoch::HazardEpoch;
use hazard_pointer::{BaseHazardNode, HazardNodeT};
use util;
use std::ptr;

type LIFONodePtr<T> = *mut LIFONode<T>;

struct LIFONode<T> {
    value: Option<T>,
    base: BaseHazardNode,
    next: LIFONodePtr<T>,
}

impl<T> HazardNodeT for LIFONode<T> {
    fn get_base_hazard_node(&self) -> *mut BaseHazardNode {
        &self.base as *const _ as *mut _
    }
}

impl<T> Drop for LIFONode<T> {
    fn drop(&mut self) {}
}

impl<T> Default for LIFONode<T> {
    fn default() -> Self {
        LIFONode {
            value: None,
            base: BaseHazardNode::default(),
            next: ptr::null_mut(),
        }
    }
}

impl<T> LIFONode<T> {
    fn next(&self) -> LIFONodePtr<T> {
        self.next
    }

    fn set_next(&mut self, next: LIFONodePtr<T>) {
        self.next = next;
    }

    fn new(value: T) -> Self {
        LIFONode {
            value: Some(value),
            base: BaseHazardNode::default(),
            next: ptr::null_mut(),
        }
    }
}

/// LockFree stack, implemented based on `HazardEpoch`
///
/// # Examples
///
/// ```
/// use rs_lockfree::lockfree_stack::LockFreeStack;
/// let mut stack = unsafe { LockFreeStack::default_new_in_stack() };
/// assert!(stack.pop().is_none());
/// stack.push(1);
/// assert_eq!(stack.pop().unwrap(), 1);
/// let test_num = 100;
/// for i in 0..test_num {
///     stack.push(i);
/// }
/// for i in 0..test_num {
///     assert_eq!(stack.pop().unwrap(), test_num - i - 1);
/// }
/// ```
///
pub struct LockFreeStack<T> {
    hazard_epoch: HazardEpoch,
    top: util::WrappedAlign64Type<LIFONodePtr<T>>,
}

impl<T> LockFreeStack<T> {
    unsafe fn atomic_load_top(&self) -> LIFONodePtr<T> {
        util::atomic_load_raw_ptr(self.top.as_ptr())
    }

    /// Return LockFreeStack in stack with default setting of HazardEpoch
    pub unsafe fn default_new_in_stack() -> LockFreeStack<T> {
        LockFreeStack {
            hazard_epoch: HazardEpoch::default_new_in_stack(),
            top: util::WrappedAlign64Type(ptr::null_mut()),
        }
    }

    /// Return LockFreeStack in heap with default setting of HazardEpoch
    pub fn default_new_in_heap() -> Box<Self> {
        unsafe { Box::new(Self::default_new_in_stack()) }
    }

    /// Push an element to the top of current stack
    pub fn push(&mut self, v: T) {
        unsafe { self.inner_push(v) }
    }

    unsafe fn inner_push(&mut self, v: T) {
        let node = Box::into_raw(Box::new(LIFONode::new(v)));
        let mut handle = 0_u64;
        self.hazard_epoch.acquire(&mut handle);
        let mut cur = self.atomic_load_top();
        let mut old = cur;
        (*node).set_next(old);
        while !{
            let (tmp, b) = util::atomic_cxchg_raw_ptr(self.top.as_mut_ptr(), old, node);
            cur = tmp;
            b
        } {
            old = cur;
            (*node).set_next(old);
        }
        self.hazard_epoch.release(handle);
    }

    /// Pop the element at the top of current queue
    pub fn pop(&mut self) -> Option<T> {
        unsafe { self.inner_pop() }
    }

    unsafe fn inner_pop(&mut self) -> Option<T> {
        let mut ret = None;
        let mut handle = 0_u64;
        self.hazard_epoch.acquire(&mut handle);
        let mut cur = self.atomic_load_top();
        let mut old = cur;
        while !cur.is_null() && !{
            let (tmp, b) = util::atomic_cxchg_raw_ptr(self.top.as_mut_ptr(), old, (*cur).next());
            cur = tmp;
            b
        } {
            old = cur;
        }
        if !cur.is_null() {
            ret = (*cur).value.take();
            assert!(ret.is_some());
            self.hazard_epoch.add_node(cur);
        }
        self.hazard_epoch.release(handle);
        ret
    }

    pub unsafe fn destroy(&mut self) {
        let mut head = *self.top;
        while !head.is_null() {
            head = Box::from_raw(head).next;
        }
        self.top = util::WrappedAlign64Type(ptr::null_mut());
    }
}

impl<T> Drop for LockFreeStack<T> {
    fn drop(&mut self) {
        unsafe {
            self.destroy();
        }
    }
}

mod test {
    use std::cell::RefCell;

    struct Node<'a, T> {
        cnt: &'a RefCell<i32>,
        v: T,
    }

    impl<'a, T> Drop for Node<'a, T> {
        fn drop(&mut self) {
            *self.cnt.borrow_mut() += 1;
        }
    }

    #[test]
    fn test_base() {
        use lockfree_stack::LockFreeStack;
        let mut queue = unsafe { LockFreeStack::default_new_in_stack() };
        assert!(queue.pop().is_none());
        queue.push(1);
        assert_eq!(queue.pop().unwrap(), 1);
        let test_num = 100;
        for i in 0..test_num {
            queue.push(i);
        }
        for i in 0..test_num {
            assert_eq!(queue.pop().unwrap(), test_num - i - 1);
        }
    }

    #[test]
    fn test_memory_leak() {
        use lockfree_stack::LockFreeStack;
        let cnt = RefCell::new(0);
        let mut queue = unsafe { LockFreeStack::default_new_in_stack() };
        let test_num = 100;
        for i in 0..test_num {
            queue.push(Node { cnt: &cnt, v: i });
        }
        assert_eq!(*cnt.borrow(), 0);
        for i in 0..test_num {
            assert_eq!(queue.pop().unwrap().v, test_num - i - 1);
        }
        assert_eq!(*cnt.borrow(), test_num);
    }
}