这是两个问题中的第二个问题(这是第一个),旨在帮助理解 Go 泛型提案示例。
特别是,到目前为止,我在理解标题为“Channels”的提案示例部分中的两段代码时遇到了麻烦:
我遇到的第二个问题是以下
Ranger
函数的定义。
也就是说,我不明白需要调用
runtime.SetFinalizer(r,r.finalize)
,实际上 finalize
类型的 *Receiver[T]
) 方法应该做的只是简单地表示接收器已完成接收值(close(r.done)
).
在我看来,通过为
*Receiver[T]
提供终结器,代码将关闭接收器的义务委托给运行时。
我理解这段代码的方式是,
*Receiver[T]
向*Sender[T]
发出信号,表示当GC确定前者不可访问时,它不会再接收任何值,即不再有可用的引用。
如果我的解释是正确的,为什么要等那么久才能让接收者发出信号已完成?难道不能以某种方式在代码中显式处理
close
操作吗?
代码:
// Ranger provides a convenient way to exit a goroutine sending values
// when the receiver stops reading them.
//
// Ranger returns a Sender and a Receiver. The Receiver provides a
// Next method to retrieve values. The Sender provides a Send method
// to send values and a Close method to stop sending values. The Next
// method indicates when the Sender has been closed, and the Send
// method indicates when the Receiver has been freed.
func Ranger[T any]() (*Sender[T], *Receiver[T]) {
c := make(chan T)
d := make(chan bool)
s := &Sender[T]{values: c, done: d}
r := &Receiver[T]{values: c, done: d}
// The finalizer on the receiver will tell the sender
// if the receiver stops listening.
runtime.SetFinalizer(r, r.finalize)
return s, r
}
// A Sender is used to send values to a Receiver.
type Sender[T any] struct {
values chan<- T
done <-chan bool
}
// Send sends a value to the receiver. It reports whether any more
// values may be sent; if it returns false the value was not sent.
func (s *Sender[T]) Send(v T) bool {
select {
case s.values <- v:
return true
case <-s.done:
// The receiver has stopped listening.
return false
}
}
// Close tells the receiver that no more values will arrive.
// After Close is called, the Sender may no longer be used.
func (s *Sender[T]) Close() {
close(s.values)
}
// A Receiver receives values from a Sender.
type Receiver[T any] struct {
values <-chan T
done chan<- bool
}
// Next returns the next value from the channel. The bool result
// reports whether the value is valid. If the value is not valid, the
// Sender has been closed and no more values will be received.
func (r *Receiver[T]) Next() (T, bool) {
v, ok := <-r.values
return v, ok
}
// finalize is a finalizer for the receiver.
// It tells the sender that the receiver has stopped listening.
func (r *Receiver[T]) finalize() {
close(r.done)
}
TLDR: 您的理解是正确的,
done
通道可能只是由接收者“手动”关闭,以表示失去兴趣(停止通信并解除发送者的职责)。
通道用于让 goroutine 以并发安全的方式进行通信。惯用的用法是发送方不断发送值,一旦没有更多的值要发送,发送方就会发出关闭通道的信号。
接收方不断从通道接收数据,直到通道关闭,这表明通道上不会(不能)再有任何值。这通常/最简单地使用通道上的
for range
来完成。
所以通常接收方必须继续接收直到通道关闭,否则发送方将永远被阻止。通常这是可以/足够的。
演示的
Ranger()
构造适用于接收方需要/可能停止通信的非一般情况。
单一通道无法让接收方向发送方发出信号:接收方已失去兴趣,并且不需要更多值。这需要一个额外的通道,接收者必须关闭该通道(当然发送者也必须监视)。只要有一个接收器,这也可以。但如果有多个接收者,关闭
done
通道会变得有点复杂:所有接收者都不能关闭 done
通道:关闭已经关闭的通道会出现恐慌。因此接收方也必须进行协调,因此只有一个接收方,或者更确切地说,协调方本身会关闭 done
通道,仅一次;这必须在所有接收者“放弃”频道之后发生。
Ranger()
可以帮助解决此问题,并以一种简单的方式通过使用终结器委托关闭 done
通道。这是可以接受的,因为通常停止通信甚至不是接收者的任务,但在极少数情况下,如果这种情况仍然出现,它将被处理(以一种简单的方式,不需要额外的,协调器 goroutine)。