关闭具有多个值的 Golang 通道

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

Close golang channel with multiple values

问题

假设我有一个发送器和任意数量的通过通道连接的接收器。当发送器完成后,它关闭通道并通知所有接收器。到目前为止都很好。

现在假设发送器希望接收器以两种不同的方式完成,比如“立即关闭”和“先完成当前任务,然后关闭”。为了实现这一点,当关闭时,它必须向所有接收器广播两个不同的值(NOW和LATER)。

在Go语言中,有一种符合惯用方式来实现这个目标。

英文:

Imagine I have one sender and arbitrary number of receivers connected via a channel. When the sender finishes it closes the channel and all receivers get notified. So far so good.

Now imagine sender wants receivers to finish in two different ways, say, "close immediately" and "first finish what you are doing, then close". To achieve that it has to broadcast two different values (NOW vs. LATER) to all receivers when shutting down.

What is the Go-idiomatic way to do this?

答案1

得分: 2

我个人会使用两个通道来信号关闭:https://play.golang.org/p/5erPW1tFXp

英文:

Personally I'd use two channels to signal shutdown: https://play.golang.org/p/5erPW1tFXp

huangapple
  • 本文由 发表于 2016年6月1日 12:54:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/37559715.html
匿名

发表评论

匿名网友

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

确定