You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What operating system and processor architecture are you using?
windows/amd64
What did you do?:
I am processing a slice of os.FileInfo by passing each by pointer ref to a goroutine.
I am getting a weird behaviour where it would try to process the same file twice.
This issue doesn't happen when passing the file to the goroutine by value instead of pointer.
Full program to reproduce the error. Two or more zip files should be in the current dir. File type doesn't matter...replace the last parameter of findFilesByExt if you're not using zip files.
package main
import (
"fmt"
"os"
"strings"
"sync"
)
func main() {
files := findFilesByExt(".", ".zip")
var wg sync.WaitGroup
for _, file := range files {
wg.Add(1)
go processFile(&file, &wg)
}
wg.Wait()
println("Done processing")
}
func processFile(file *os.FileInfo, wg *sync.WaitGroup) {
defer wg.Done()
println("Processing " + (*file).Name())
}
func findFilesByExt(directory string, extension string) []os.FileInfo {
f, err := os.Open(directory)
if err != nil {
fmt.Fprintf(os.Stderr, "could not open directory: %v\n", err)
return nil
}
defer f.Close()
entries, err := f.Readdir(0)
if err != nil {
fmt.Fprintf(os.Stderr, "could not read dir: %v\n", err)
}
var found []os.FileInfo
for _, file := range entries {
if strings.HasSuffix(file.Name(), extension) && !file.IsDir() {
found = append(found, file)
}
}
return found
}
Thank you for raising this issue. This is not a bug in Go or the os package, what is occurning is on each iteration of the range loop the variable file is reused, thus its address does not change, hence the value pointed to by the pointer passed into processFile is overwritten on each range loop.
I'm going to close this issue as, while suprising, not a bug. Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.
What version of Go are you using:
go1.15
What operating system and processor architecture are you using?
windows/amd64
What did you do?:
I am processing a slice of os.FileInfo by passing each by pointer ref to a goroutine.
I am getting a weird behaviour where it would try to process the same file twice.
This issue doesn't happen when passing the file to the goroutine by value instead of pointer.
Full program to reproduce the error. Two or more zip files should be in the current dir. File type doesn't matter...replace the last parameter of findFilesByExt if you're not using zip files.
What did you expect to see?
What did you see instead?
The text was updated successfully, but these errors were encountered: