'Are function variables concurrency-safe in golang?
I have following types declared
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 1:[1]
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.
Solution 2:[2]
Yes, your code works.
You would have issues if a goroutine tried to reassign the value of FuncXX
while another one tries to start that same FuncXX
-- this would be a race condition.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | LeGEC |