-
Notifications
You must be signed in to change notification settings - Fork 20
/
stack.go
53 lines (47 loc) · 1.11 KB
/
stack.go
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
// Copyright 2020 The golang.design Initiative authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
package lockfree
import (
"sync/atomic"
"unsafe"
)
// Stack implements lock-free freelist based stack.
type Stack struct {
top unsafe.Pointer
len uint64
}
// NewStack creates a new lock-free queue.
func NewStack() *Stack {
return &Stack{}
}
// Pop pops value from the top of the stack.
func (s *Stack) Pop() interface{} {
var top, next unsafe.Pointer
var item *directItem
for {
top = atomic.LoadPointer(&s.top)
if top == nil {
return nil
}
item = (*directItem)(top)
next = atomic.LoadPointer(&item.next)
if atomic.CompareAndSwapPointer(&s.top, top, next) {
atomic.AddUint64(&s.len, ^uint64(0))
return item.v
}
}
}
// Push pushes a value on top of the stack.
func (s *Stack) Push(v interface{}) {
item := directItem{v: v}
var top unsafe.Pointer
for {
top = atomic.LoadPointer(&s.top)
item.next = top
if atomic.CompareAndSwapPointer(&s.top, top, unsafe.Pointer(&item)) {
atomic.AddUint64(&s.len, 1)
return
}
}
}