如何在不阻塞的情况下确定 goroutine 是否已完成?
到目前为止,我看到的所有示例都涉及阻塞以获取结果(通过 <-chan
运算符)。
我当前的方法涉及传递一个指向结构的指针:
type goresult struct {
result resultType;
finished bool;
}
goroutine 在完成时写入该结构。然后只要方便就可以简单地检查finished
。你有更好的选择吗?
我真正的目标是 Qt 风格的信号槽系统。我有预感,该解决方案看起来几乎微不足道(chan
具有很多 未开发的潜力),但我还不够熟悉该语言,无法弄清楚它。
All the examples I've seen so far involve blocking to get the result (via the <-chan
operator).
My current approach involves passing a pointer to a struct:
type goresult struct {
result resultType;
finished bool;
}
which the goroutine writes upon completion. Then it's a simple matter of checking finished
whenever convenient. Do you have better alternatives?
What I'm really aiming for is a Qt-style signal-slot system. I have a hunch the solution will look almost trivial (chan
s have lots of unexplored potential), but I'm not yet familiar enough with the language to figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用“comma, ok”模式(请参阅他们的页面“ effective go”):
You can use the "comma, ok" pattern (see their page on "effective go"):
Select statements 允许您一次检查多个通道,并随机选择一个分支(等待通信的地方):
Select statements allows you to check multiple channels at once, taking a random branch (of the ones where communication is waiting):
您还可以使用 len 查看通道缓冲区以查看它是否包含任何内容:
这不会触及通道缓冲区,与
foo,gotValue := <- ch
不同,它会在 < 时删除值代码>gotValue == true。You can also peek at the channel buffer to see if it contains anything by using len:
This won't touch the channel buffer, unlike
foo, gotValue := <- ch
which removes a value whengotValue == true
.