Edit:: Full code here
I have the following piece of code:
filelistchan := make(chan string)
for _, dir := range tld {
w.Add(1)
go GetFileList(dir, filelistchan, w)
}
for ;; {
file, ok := <- filelistchan
fmt.Println(ok)
switch ok {
case false:
break
default:
fmt.Println(file)
}
}
w.Wait()
and GetFileList function is
func GetFileList(dir string, filelistchan chan string, w sync.WaitGroup) {
defer fmt.Println("finishing from", dir)
defer w.Done()
fmt.Println("Searching in", dir)
filelist := []string{}
filepath.Walk(dir, func(path string, f os.FileInfo, err error) error{
filelist = append(filelist, path)
return nil
})
for _, file := range filelist {
fmt.Println(file)
filelistchan <- file
}
}
I am calling GetFileList
function parallely inside a forloop, to get the list of files inside them. It works fine till the last directory, however, once the last directory is completed, it gives an error
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
and when I am printing the ok, I could see that false is never getting printed from the goroutine once it is finishing the job. I am unable to figure out what I am doing wrong here. I tried close(filelistchan)
inside the GetFileList
function, but it gives another error after the first goroutine exits, saying write on closed channel
and attempting to close a closed channel
. Can someone please explain, what is the best idiomatic way to get this working?