私は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
}()
}
私はこれを自分で考え出したと思うが、それをテストし、最初にうまくいくことを確認する。 –