Is this the correct way of using concurrency in this case?

I’m using WaitGroup to concurrently populate a struct instance. Each goroutine will populate separate fields of the struct. Do I have to lock the struct instance before using it?

package main

import (
  "fmt"
  "sync"
)

type st struct {
  field1 string
  field2 string
  field3 string
}

func main() {
  var wg sync.WaitGroup
  wg.Add(3)
  s := &st{}

  go func() {
    defer wg.Done()
    s.field1 = "asdf"
  }()

  go func() {
    defer wg.Done()
    s.field2 = "qwert"
  }()

  go func() {
    defer wg.Done()
    s.field3 = "zxcv"
  }()

  wg.Wait()
  fmt.Println("%#v", s)
}

No, as you’re accessing separate attributes in each routine that’s fine.

1 Like

You can always see what the race detector says:

go run -race main.go
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.