1 Star 0 Fork 0

lichun-123 / leaf

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
go.go 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
lichun-123 提交于 2023-10-05 17:04 . proto update
package g
import (
"container/list"
"gitee.com/lichun-123/leaf/conf"
"gitee.com/lichun-123/leaf/log"
"runtime"
"sync"
)
// one Go per goroutine (goroutine not safe)
type Go struct {
ChanCb chan func()
pendingGo int
}
type LinearGo struct {
f func()
cb func()
}
type LinearContext struct {
g *Go
linearGo *list.List
mutexLinearGo sync.Mutex
mutexExecution sync.Mutex
}
func New(l int) *Go {
g := new(Go)
g.ChanCb = make(chan func(), l)
return g
}
func (g *Go) Go(f func(), cb func()) {
g.pendingGo++
go func() {
defer func() {
g.ChanCb <- cb
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
f()
}()
}
func (g *Go) Cb(cb func()) {
defer func() {
g.pendingGo--
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
if cb != nil {
cb()
}
}
func (g *Go) Close() {
for g.pendingGo > 0 {
g.Cb(<-g.ChanCb)
}
}
func (g *Go) Idle() bool {
return g.pendingGo == 0
}
func (g *Go) NewLinearContext() *LinearContext {
c := new(LinearContext)
c.g = g
c.linearGo = list.New()
return c
}
func (c *LinearContext) Go(f func(), cb func()) {
c.g.pendingGo++
c.mutexLinearGo.Lock()
c.linearGo.PushBack(&LinearGo{f: f, cb: cb})
c.mutexLinearGo.Unlock()
go func() {
c.mutexExecution.Lock()
defer c.mutexExecution.Unlock()
c.mutexLinearGo.Lock()
e := c.linearGo.Remove(c.linearGo.Front()).(*LinearGo)
c.mutexLinearGo.Unlock()
defer func() {
c.g.ChanCb <- e.cb
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
e.f()
}()
}
Go
1
https://gitee.com/lichun-123/leaf.git
git@gitee.com:lichun-123/leaf.git
lichun-123
leaf
leaf
v0.0.41

搜索帮助

53164aa7 5694891 3bd8fe86 5694891