英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论