【发布时间】:2013-04-12 15:46:34
【问题描述】:
就我而言,我有数千个 goroutine 同时作为 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++ {
channels[i] <- 0
}
channels_mutex.Unlock()
}
现在的问题是,由于<- 总是在读取时阻塞,所以每次去sync_stat := <- channel 都是阻塞的。我知道如果频道关闭了它不会被阻止,但是由于我必须在work()退出之前使用这个频道,并且我没有找到任何方法来重新打开已关闭的频道。
我怀疑自己走错路了,因此感谢您的帮助。是否有一些“优雅”的方式来暂停和恢复任何其他 goroutine?
【问题讨论】: