我怎么知道一个门厅是否完成,没有阻塞? [英] How do I find out if a goroutine is done, without blocking?

查看:126
本文介绍了我怎么知道一个门厅是否完成,没有阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我所见过的所有示例都涉及阻塞以获取结果(通过< -chan 运算符)。



我现在的方法是将一个指针传递给一个struct:

  type goresult struct {
result与resultType;
完成了bool;
}

在goroutine完成时写入。然后,只要方便,只需检查完成即可。你有更好的选择吗?



我真正想要的是一个Qt风格的信号插槽系统。我有一个预感,解决方案看起来几乎是微不足道的( chan s有很多潜在未知空间),但我还不太熟悉你可以使用逗号,确定模式(请参阅 effective go ):

  foo:=<  -  ch; //这块。 
foo,ok:=< - ch; //这将立即返回。


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 (chans have lots of unexplored potential), but I'm not yet familiar enough with the language to figure it out.

解决方案

You can use the "comma, ok" pattern (see their page on "effective go"):

foo     := <- ch; // This blocks.
foo, ok := <- ch; // This returns immediately.

这篇关于我怎么知道一个门厅是否完成,没有阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆