Are function variables are concurrent safe in golang?

Issue

I have following types delcared

type TestFn func(id int, ctx context.Context) error

var Func1 = TestFn(func(id int, ctx context.Context) error {
  // do some work -- the execution block is concurrent safe
}

var Func2 = TestFn(func(id int, ctx context.Context) error {
  // do some work
}

var Func3 = TestFn(func(id int, ctx context.Context) error {
  // do some work
}

func Execute()
   for i := 0; i < 5; i++ {
      go Func1(i, ctx)
      go Func2(i, ctx)
      go Func3(i, ctx)
   }
}

As Func1, Func2, Func3 are global variables and assigned to functions, Can I run same function in multiple go routines with different params?

Solution

The rule is simple: no value is safe for concurrent access from multiple goroutines (without synchronization) where at least one of the accesses is a write.

Your example only reads the function variables, so it is safe. If there would be a goroutine running concurrently with the execution of Execute() that would modify the function variables, that would not be safe. But this doesn’t happen in your example.

Note: your function variables are of course written once, during package initialization. That happens in a single goroutine before main() starts.

Answered By – icza

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.