Hi Guys,wanted to see if i making correct assumptions regarding mutexes and structuresvar globalMutex sync.Mutex{}type abc struct {
a int
b intmu sync.Mutex{}
}1. First is self explanatory, array of structures all needs to be protected by mutexx := []abc{}x = append(x, abc{}) // <- This needs to be done inside globalMutex.Lock
x[0].a = 10 // <- This needs to be done inside globalMutex.Lock, as the array/slice is holding the data (?)
- Reading x[0].a would require globalMutex.RLock
- Mu is not necessary
2. Array of pointer to structuresy := []*abc{}
_tmp := &abc{}
y = append(y, _tmp) <- This needs to be put inside globalMutex.Lock Mutex
y[0].b = 1 <- This can be put inside globalMutex.RLock and we also need mu.Lock (as it's sufficient to read abc pointer and the pointer will never change after the element gets added to the list)
- Reading y[0].b would require RLock on both globalMutex and mu
Or maybe it's better to just use generic read-write locks for everything and don't bother?Thanks
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ffc7c10e-ddb9-4bc5-a545-2a1ce7b22bfbn%40googlegroups.com.
Thanks, very good point about including the structure by-value.As for using the structure via pointer> You don't need to rlock the global mutex. Even if another goroutine appends to> the slice and slice gets reallocated, this code will still be pointing to the correct element.I'd assume I'll still need the global RLock, as len will not be synchronized. And moreover if i shrink the array by 1 and then append one element, i'll be changing the pointer in-place which could result in some pseudo-random memory location being accessed.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4c03668d-58b7-4629-8c27-001473005145n%40googlegroups.com.