If I am writing a function to modify a variable's value dynamically, how would I go about making that function safe for concurrent use. For example, consider the following snippet:
func set(v, d interface{}) error {
val := reflect.ValueOf(v)
dst := reflect.ValueOf(d).Elem()
if dst.Type() != val.Type() {
return fmt.Errorf("incompatible types - %s %s", dst.Type(), val.Type())
}
dst.Set(val)
return nil
}
This function will be called in the following manner:
i := 1
var j int
_ = set(i, &j)
Working code: https://play.golang.org/p/XjlHrDLFqd
How safe would it be to change i
concurrently? reflect.Value
docs say the following:
A Value can be used concurrently by multiple goroutines provided that the underlying Go value can be used concurrently for the equivalent direct operations.
Which leads me to believe that locking would be required. If so, where would the locking part go? Is it required to be maintained until the value (concrete) completely makes it through the reflection section? For example, in the above example, is it OK to keep a lock through out set
's execution?
Also, what are some underlying Go values that cannot be used concurrently (as mentioned in the docs bit above)?