0

I want to concurrently parse files with the parseFile() function and assign its return values to the fields of a struct with type fileInfo which is located in a slice of structs files []fileInfo.
The files struct is prepopulated with fileInfo elements and I want to update the fields A,B of each fileInfo element in the slice.

Question: Is my code idiomatic for Go or should it be solved differently?

I am using sync.Mutex for now to lock the struct in the slice but I wonder if there is a better solution for this task or if the code is even correct and does not just work by chance.

type fileInfo struct {
    A           []string
    B           string
    Path        string
    UpdateMutex sync.Mutex
}

func parseFile(filePath string) ([]string, string, error) {
    var a []string
    var b string
    var err error
    //do some parsing
    //...

    return a, b, err
}

func main() {
    var files []fileInfo
    //pre-populate fileInfo

    wg := new(sync.WaitGroup)
    for i, _ := range files {
        wg.Add(1)
        go func(pFile *fileInfo) {

            var err error
            defer wg.Done()

            pFile.UpdateMutex.Lock()
            pFile.A, pFile.B, err = parseFile(pFile.Path)
            pFile.UpdateMutex.Unlock()

            if err != nil {
                fmt.Println(err)
            }
        }(&files[i])
    }
    //more work
    //...
    wg.Wait()
    //continue
}

I thought about using channels but I can't quite wrap my head around how one can update a specific files[i].A using a channel.

armmie
  • 25
  • 2
  • 8
  • 1
    Your solution works at first glance, but also note that you don't even need the mutex. Each slice element act as a distinct variable, so if each goroutine writes only its own designated element, no locking is necessary. See [Can I concurrently write different slice elements](https://stackoverflow.com/questions/49879322/can-i-concurrently-write-different-slice-elements/49879469#49879469). – icza Oct 10 '19 at 15:24
  • The mutex is not needed for the code presented because there is no concurrent access to an individual element of `files`. – Charlie Tumahai Oct 10 '19 at 15:25
  • And the only mutable part of `fileInfo` is the slice. – Adrian Oct 10 '19 at 15:41
  • Thanks, then I will stick with my current solution and remove the mutex. – armmie Oct 10 '19 at 21:58

0 Answers0