2014-11-11 15:07:54 -07:00
|
|
|
// Copyright 2012 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Lock-free stack.
|
|
|
|
|
|
|
|
package runtime
|
|
|
|
|
2015-11-02 12:09:24 -07:00
|
|
|
import (
|
|
|
|
"runtime/internal/atomic"
|
|
|
|
"unsafe"
|
|
|
|
)
|
2014-11-11 15:07:54 -07:00
|
|
|
|
2017-03-07 14:38:29 -07:00
|
|
|
// lfstack is the head of a lock-free stack.
|
|
|
|
//
|
|
|
|
// The zero value of lfstack is an empty list.
|
|
|
|
//
|
|
|
|
// This stack is intrusive. Nodes must embed lfnode as the first field.
|
|
|
|
//
|
|
|
|
// The stack does not keep GC-visible pointers to nodes, so the caller
|
|
|
|
// is responsible for ensuring the nodes are not garbage collected
|
|
|
|
// (typically by allocating them from manually-managed memory).
|
|
|
|
type lfstack uint64
|
|
|
|
|
|
|
|
func (head *lfstack) push(node *lfnode) {
|
2014-11-11 15:07:54 -07:00
|
|
|
node.pushcnt++
|
2014-11-14 10:55:23 -07:00
|
|
|
new := lfstackPack(node, node.pushcnt)
|
2016-04-06 02:43:23 -06:00
|
|
|
if node1 := lfstackUnpack(new); node1 != node {
|
2017-03-07 14:38:29 -07:00
|
|
|
print("runtime: lfstack.push invalid packing: node=", node, " cnt=", hex(node.pushcnt), " packed=", hex(new), " -> node=", node1, "\n")
|
|
|
|
throw("lfstack.push")
|
2014-11-19 09:30:58 -07:00
|
|
|
}
|
2014-11-11 15:07:54 -07:00
|
|
|
for {
|
2017-03-07 14:38:29 -07:00
|
|
|
old := atomic.Load64((*uint64)(head))
|
2014-11-15 06:00:38 -07:00
|
|
|
node.next = old
|
2017-03-07 14:38:29 -07:00
|
|
|
if atomic.Cas64((*uint64)(head), old, new) {
|
2014-11-11 15:07:54 -07:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-07 14:38:29 -07:00
|
|
|
func (head *lfstack) pop() unsafe.Pointer {
|
2014-11-11 15:07:54 -07:00
|
|
|
for {
|
2017-03-07 14:38:29 -07:00
|
|
|
old := atomic.Load64((*uint64)(head))
|
2014-11-11 15:07:54 -07:00
|
|
|
if old == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2016-04-06 02:43:23 -06:00
|
|
|
node := lfstackUnpack(old)
|
2015-11-02 12:09:24 -07:00
|
|
|
next := atomic.Load64(&node.next)
|
2017-03-07 14:38:29 -07:00
|
|
|
if atomic.Cas64((*uint64)(head), old, next) {
|
2014-11-11 15:07:54 -07:00
|
|
|
return unsafe.Pointer(node)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-03-07 14:38:29 -07:00
|
|
|
|
|
|
|
func (head *lfstack) empty() bool {
|
|
|
|
return atomic.Load64((*uint64)(head)) == 0
|
|
|
|
}
|
2017-12-03 17:28:28 -07:00
|
|
|
|
|
|
|
// lfnodeValidate panics if node is not a valid address for use with
|
|
|
|
// lfstack.push. This only needs to be called when node is allocated.
|
|
|
|
func lfnodeValidate(node *lfnode) {
|
|
|
|
if lfstackUnpack(lfstackPack(node, ^uintptr(0))) != node {
|
|
|
|
printlock()
|
|
|
|
println("runtime: bad lfnode address", hex(uintptr(unsafe.Pointer(node))))
|
|
|
|
throw("bad lfnode address")
|
|
|
|
}
|
|
|
|
}
|