通知所有的goroutine

huangapple go评论92阅读模式
英文:

Notify all goroutines

问题

我正在使用Go语言编写一个TCP服务器。现在我想通知所有与客户端通信的goroutine断开连接,丢弃它们所拥有的内容并停止运行。

关闭一个通道是通知它们的一种方式。

问题是:这是Go语言的惯用方式吗?如果我错了,那么我应该怎么做(用于通知所有goroutine的类似于.NET中的ManualResetEvent的东西)?

注意:我是一个Go语言新手,刚刚开始学习,并且之前用C#编写过TCP服务器。

英文:

I am working on a TCP Server in Go. Now I want to notify all goroutines that are talking to clients to drop their connections, dump what they've got and stop.

Closing a channel is a way to notify all of them.

Question is: Is that idiomatic Go? If I am wrong; then what should I do (for notifying all of goroutines - something like ManualResetEvent in .NET)?

Note: I am a Go newbie, just learning and started with TCP Server because I have written that before in C#.

答案1

得分: 6

是的,关闭通道是Go语言中协程之间通信的一种惯用方式。

在每个协程启动时,您需要将一个通道传递给它,并在每个网络事件之后使用select调用来检查通道。

您还需要设置网络事件的超时,以防止连接永远挂起。

英文:

Yes, closing a channel is an idiomatic Go way of communicating between Goroutines.

You'll need to pass a channel into each goroutine as it launches and check the channel with the select call after each network event.

You'll also want to set timeouts on network events so that you don't have connections hanging around forever.

答案2

得分: 1

从Go 1.7开始,您可以使用context包。

英文:

As of Go 1.7, you can use the context package.

huangapple
  • 本文由 发表于 2013年3月13日 05:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/15373011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定