1 Star 0 Fork 0

lesenro/evio

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
notequeue.go 988 Bytes
一键复制 编辑 原始数据 按行查看 历史
Josh Baker 提交于 2018-05-23 16:49 . Added multithreaded support
// Copyright 2018 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package internal
import (
"runtime"
"sync/atomic"
)
// this is a good candiate for a lock-free structure.
type spinlock struct{ lock uintptr }
func (l *spinlock) Lock() {
for !atomic.CompareAndSwapUintptr(&l.lock, 0, 1) {
runtime.Gosched()
}
}
func (l *spinlock) Unlock() {
atomic.StoreUintptr(&l.lock, 0)
}
type noteQueue struct {
mu spinlock
notes []interface{}
}
func (q *noteQueue) Add(note interface{}) (one bool) {
q.mu.Lock()
q.notes = append(q.notes, note)
n := len(q.notes)
q.mu.Unlock()
return n == 1
}
func (q *noteQueue) ForEach(iter func(note interface{}) error) error {
q.mu.Lock()
if len(q.notes) == 0 {
q.mu.Unlock()
return nil
}
notes := q.notes
q.notes = nil
q.mu.Unlock()
for _, note := range notes {
if err := iter(note); err != nil {
return err
}
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/lesenro/evio.git
git@gitee.com:lesenro/evio.git
lesenro
evio
evio
v1.0.3

搜索帮助