go - 是否关闭通道块直到接收器读取它
问题描述
我已经实现了一种通过关闭通道来关闭服务器的方法,因此其他 goroutines 读取关闭的通道然后退出。关闭后,我需要对服务器数据进行一些清理,如果close()
阻塞直到所有其他 goroutine 读取关闭的通道,我可以无锁访问数据。所以问题是:关闭通道会阻塞直到接收器从中读取吗?下面是示例代码:
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()
}
解决方案
不,请改用 a sync.WaitGroup
。
推荐阅读
- react-native - 可能未处理的承诺拒绝 React Native
- mysql - 组合值的 MySQL 导入查询
- typescript - 是否有与流式 CLI 工具等效的 TypeScript?
- android - onNavigationItemSelected 不适用于导航抽屉
- c++ - C++ 试图实现一个矩阵
- r - R ggplot2 使用 RStudio 图表缩放设置保存图表
- javascript - 如何为偶数和奇数创建一个 React 类
- mongodb - 如何返回包含相同值但在 MongoDB 中的不同字段中的所有对象?
- c# - 使用双区域创建平均成绩
- awkward-array - 从尴尬的数组中删除 none