我实现了一种通过关闭 channel 来关闭服务器的方法,以便其他 goroutine 读取关闭的 channel 然后退出。关闭后,我需要对服务器数据进行一些清理,如果 close()
阻塞直到所有其他 goroutine 读取关闭的 channel ,我就可以无锁地访问数据。所以问题是:关闭 channel 是否会阻塞直到接收者从中读取数据?下面是示例代码:
package main
type server struct {
chStop chan struct{}
data map[int]interface{}
}
func newServer() *server {
return &server {
chStop: make(chan struct{})
}
}
func (s *server) stop() {
close(s.chStop)
// do something with s.data
...
// if other goroutines already read closed s.chStop and exited,
// we can access s.data without lock
}
func (s *server) run2() {
...
for {
select{
case <-s.chStop:
return
case <- other channel:
// access s.data with lock
}
}
}
func (s *server) run() {
ch := make(chan struct{})
...
for {
select{
case <-s.chStop:
return
case <- ch:
// access s.data with lock
}
}
}
func main() {
s := newServer()
go s.run()
go s.run2()
s.stop()
}
最佳答案
没有。使用sync.WaitGroup
相反。
关于go - 是否关闭 channel 阻塞直到接收者读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52146709/