Reputation: 1694
There is a parm which is read more and written less, And I don't want to use a mutex .I got it done like this by unsafe
and atomic
:
type tmp struct {
}
var value unsafe.Pointer
func GetValue() *tmp {
return (*tmp)(atomic.LoadPointer(&value))
}
func SetValue(p *tmp) {
atomic.StorePointer(&value, unsafe.Pointer(p))
}
Is this thread-safe ? and atomic.StorePointer happen before
atomic.LoadPointer ?
Upvotes: 2
Views: 1391
Reputation: 1694
According to https://code.google.com/p/go/issues/detail?id=5045
Regarding Add/CAS, it should be formulated in in more general terms, along the
lines of: at atomic operation that stores a value (incl ADD/CAS) happens before
atomic operation that reads that value from the memory location (incl ADD/CAS).
I think We can use atomic to ensure it thread-safe.
Upvotes: 0
Reputation: 73286
As far as I know, storing and retrieving a pointer using atomic.LoadPointer and atomic.StorePointer is thread-safe (in the sense that the pointer itself will not be corrupted).
Of course, the pointed object must be immutable, and this is not enforced by this mechanism. This is your job to be sure that updating the configuration will result in a new object being created before calling UpdateConfig.
However, the main issue is the code relies on unsafe operations. Making it type safe is difficult, since two pointers have actually to be stored (one for the object, one for the type). Atomic pointer operations are not enough anymore to guarantee the consistency.
This is why a specific type has been recently added in the sync/atomic package: the sync.Value type. It is designed exactly to do what you want (i.e. optimizing access to mostly constant data).
You can find an example here: http://golang.org/pkg/sync/atomic/#example_Value_config
If you look in the implementation, you will realize why atomic pointer operations alone are not enough to implement a type safe mechanism.
Upvotes: 2
Reputation: 49255
It will be thread safe in the sense that you don't know what happens first, but the updating is atomic. Have you considered using a RWMutex instead? This won't lock readers unless there's a write going on.
Upvotes: 2