go中如何等待低延迟的线程?
我一直在尝试在 Go 中创建一个简单的事件循环包装器。但我被难住了,我应该如何跟踪当前线程中的操作? 我希望 CurrentTick 运行一个函数,即使调用函数退出,也不会启动下一个刻度,直到 CurrentTick 运行的所有函数退出。我想我可以使用互斥体来监视线程数量,但我意识到如果我不断地检查它会限制 CPU 的性能。如果我使用 time.Sleep 它将是潜伏的。你会如何解决这个问题?
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
}()
}
I've been trying to create a simple event loop wrapper in Go. But I got stumped, how was I supposed to keep track of operations in the current thread?
I wanted CurrentTick to run a function, and even if the calling function quits, not start the next tick until all functions run by CurrentTick quit. I thought I might use a mutex to monitor the number of threads, but I realized if I kept checking that over and over it would throttle the CPU. If I used time.Sleep it would be latent. How would you solve the problem?
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
}()
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解你的意图,我认为你把事情过于复杂化了。我会这样做:
根据您的使用情况,您可能需要添加一些同步,以确保循环中的所有任务在程序退出之前完成。
If I understand your intent, I think you're overcomplicating things. I'd do it like this:
Depending on your use, you may need to add some synchronization to make sure all tasks in the loop finish before your program exits.
在遇到很多问题和随机问题(包括使用 15 作为长度而不是容量)之后,我自己解决了这个问题...似乎您只是在递减计数器后有一个线程发送消息。 (loop.tick 部分可以内联,但我不担心这一点)
注意:这仍然有很多其他问题。
I figured it out myself, after a lot of problems and random issues including using 15 as length instead of capacity... Seems you just have a thread send a message after you decrement the counter. (the loop.tick part could be inlined, but I'm not worried about that)
Note: this still has lots of other problems.