1 Star 0 Fork 0

nggs / protoactor-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
mpsc.go 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
lwj8507 提交于 2018-04-21 11:34 . init
// Package mpsc provides an efficient implementation of a multi-producer, single-consumer lock-free queue.
//
// The Push function is safe to call from multiple goroutines. The Pop and Empty APIs must only be
// called from a single, consumer goroutine.
//
package mpsc
// This implementation is based on http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue
import (
"sync/atomic"
"unsafe"
)
type node struct {
next *node
val interface{}
}
type Queue struct {
head, tail *node
}
func New() *Queue {
q := &Queue{}
stub := &node{}
q.head = stub
q.tail = stub
return q
}
// Push adds x to the back of the queue.
//
// Push can be safely called from multiple goroutines
func (q *Queue) Push(x interface{}) {
n := &node{val: x}
// current producer acquires head node
prev := (*node)(atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.head)), unsafe.Pointer(n)))
// release node to consumer
prev.next = n
}
// Pop removes the item from the front of the queue or nil if the queue is empty
//
// Pop must be called from a single, consumer goroutine
func (q *Queue) Pop() interface{} {
tail := q.tail
next := (*node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&tail.next)))) // acquire
if next != nil {
q.tail = next
v := next.val
next.val = nil
return v
}
return nil
}
// Empty returns true if the queue is empty
//
// Empty must be called from a single, consumer goroutine
func (q *Queue) Empty() bool {
tail := q.tail
next := (*node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&tail.next))))
return next == nil
}
1
https://gitee.com/nggs/protoactor-go.git
git@gitee.com:nggs/protoactor-go.git
nggs
protoactor-go
protoactor-go
491bbc3fee09

搜索帮助