I started learning go recently and I am stuck on a problem. I have a simple go routine which either returns or pushes value to a channel. And my main fn delegates work to this routine till it meets condition or data is exhausted. This code seem to deadlock on "found" channel. What am I doing wrong?
- There are multiple workers
- Item can be found in more than one worker at the same time
- Once item is found, all workers should be stopped.
.
func workerRoutine(data Data, found chan bool, wg *sync.WaitGroup){
defer (*wg).Done()
// data processing
// return on false
// multiple routines can set this at the same time
found <-true
}
func main {
// ....
found:=make(chan bool)
var wg sync.WaitGroup
itemFound:=false
Loop:
for i:=0; i<limit; i++ {
select {
case <-found:
itemFound = true
break Loop
default:
if(some_check) {
wg.Add(1)
go workerRoutine(mdata,found,&wg)
}
}
}
wg.Wait()
// use itemFound
}