我一直试图在Go中创建一个简单的事件循环包装器。但是我被困住了,我该如何跟踪当前线程中的操作? 我想让CurrentTick运行一个函数,并且即使调用函数退出,也不会开始下一个滴答,直到CurrentTick运行的所有函数都退出。我想我可能会使用一个互斥体来监视线程的数量,但是我意识到如果我一直在检查反复会调整CPU。如果我用了时间。睡觉它会是潜伏的。你将如何解决这个问题?如何等待低延迟的线程去?
package eventloop
import (
"reflect"
)
type eventLoop *struct{
functions []reflect.Value
addFunc chan<-/*3*/ reflect.Value
mutex chan/*1*/ bool
threads int
}
func NewEventLoop() eventLoop {
var funcs chan reflect.Value
loop := eventLoop{
[]Reflect.Value{},
funcs = make(chan reflect.Value, 3),
make(chan bool, 1),
0,
}
go func(){
for {
this.mutex <- 1
if threads == 0 {
}
}
}
}
func (this eventLoop) NextTick(f func()) {
this.addFunc <- reflect.ValueOf(f)
}
func (this eventLoop) CurrentTick(f func()) {
this.mutex <- 1
threads += 1
<-this.mutex
go func() {
f()
this.mutex <- 1
threads -= 1
<-this.mutex
}()
}
我想我自己想到了这一点,但我会测试它,并确保它的工作第一,如果它生病发布它作为答案。 –