在Golang中,如果某个频道channel已关闭,我仍然可以使用以下语法从中读取它,我可以测试ok它是否已关闭.
value, ok := <- channel
if !ok {
// channel was closed and drained
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我不知道某个频道是否已关闭并盲目写入,我可能会收到错误.我想知道是否有任何方法可以测试通道,只有当它没有关闭时才写入它.我问这个问题是因为有时候我不知道goroutine中是否关闭了一个频道.
就我而言,我有成千上万的goroutines同时工作work().我也有一个sync()goroutine.当sync启动时,我需要任何其他的goroutine同步作业完成后暂停了一段时间.这是我的代码:
var channels []chan int
var channels_mutex sync.Mutex
func work() {
channel := make(chan int, 1)
channels_mutex.Lock()
channels = append(channels, channel)
channels_mutex.Unlock()
for {
for {
sync_stat := <- channel // blocked here
if sync_stat == 0 { // if sync complete
break
}
}
// Do some jobs
if (some condition) {
return
}
}
}
func sync() {
channels_mutex.Lock()
// do some sync
for int i := 0; i != len(channels); i++ …Run Code Online (Sandbox Code Playgroud)