When changing a card m that has parallel records, including those that can be deleted from the card, is it safe to stream ?:
for k, v := range m { ... }
I think that for thread safety, I need other possible authors to not change the value of v while I am reading it, and (when using the mutex and because locking is a separate step), make sure that key k is still on the map. For instance:
for k := range m { m.mutex.RLock() v, found := m[k] m.mutex.RUnlock() if found { ...
(Suppose other authors block the entry m before changing v .) Is there a better way?
Edit to add: I know that cards are not thread safe. However, they are thread safe in one direction, according to the Go specification at http://golang.org/ref/spec#For_statements (search "If map entries have not yet been deleted during the iteration"). This page shows that code using range does not have to worry about other goroutines inserting or removing from the map. My question is that this thread safety extends to v , so that I can get v to be read only using only for k, v := range m and another thread protected mechanism? I created some test code to try to cause the application to crash, to prove that it does not work, but even obviously unsafe code works (many goroutines violently change the same value of the card without a lock mechanism in place). I could not get Go to crash!
source share