// 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 runtimeimport ()// 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// must ensure the nodes are allocated outside the Go heap.type lfstack uint64func ( *lfstack) ( *lfnode) { .pushcnt++ := lfstackPack(, .pushcnt)for { := atomic.Load64((*uint64)()) .next = ifatomic.Cas64((*uint64)(), , ) {break } }}func ( *lfstack) () unsafe.Pointer {varuint32// TODO: tweak backoff parameters on other architectures.ifGOARCH == "arm64" { = 128 }for { := atomic.Load64((*uint64)())if == 0 {returnnil } := lfstackUnpack() := atomic.Load64(&.next)ifatomic.Cas64((*uint64)(), , ) {returnunsafe.Pointer() }// Use a backoff approach to reduce demand to the shared memory location // decreases memory contention and allows for other threads to make quicker // progress. // Read more in this Arm blog post: // https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/multi-threaded-applications-armprocyield()// Increase backoff time. += / 2 }}func ( *lfstack) () bool {returnatomic.Load64((*uint64)()) == 0}// 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( *lfnode) {if , , := findObject(uintptr(unsafe.Pointer()), 0, 0); != 0 {throw("lfstack node allocated from the heap") }lfstackPack(, ^uintptr(0))}func lfstackPack( *lfnode, uintptr) uint64 {returnuint64(taggedPointerPack(unsafe.Pointer(), &(1<<tagBits-1)))}func lfstackUnpack( uint64) *lfnode {return (*lfnode)(taggedPointer().pointer())}
The pages are generated with Goldsv0.8.3-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.