(I posted this to r/golang but I didn't get what I consider a definitive 
answer).

I know that maps aren't safe for concurrent access, but I've always thought 
this meant only that you can't add or delete keys concurrently. 

Let's say I already have a map[string]int that has been filled with keys 
that are file names. I won't be adding any more keys. I want to add an int 
value for each existing key to contain the file size. Could I do this by 
running a bunch of go routines, one per file name key? (Let's ignore for 
now whether doing this would be any faster than not using go routines.)

The Go Language spec doesn't directly define the rules for concurrent 
memory safety. Instead, those rules are explicitly defined in the Go Memory 
Model (https://go.dev/ref/mem). I looked there but I wasn't able to find 
what I was looking for.  The Go FAQ has a section on Atomic Maps (
https://go.dev/doc/faq#atomic_maps)  <https://go.dev/doc/faq#atomic_maps>
says 

"As long as all goroutines are only reading—looking up elements in the map, 
including iterating through it using a for range loop—and not changing the 
map by assigning to elements or doing deletions, it is safe for them to 
access the map concurrently without synchronization."

The question here is what is meant by "assigning to elements".

My thinking is that this should be allowed because adding a file name to 
the map should have also added space for an int value. So, I'd just be 
modifying this int, and not changing the hash table data structure. Is this 
correct?


Cordially,

Jon Forrest



-- 
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 [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/873345e3-4dc6-4578-a408-b356f3ab04abn%40googlegroups.com.

Reply via email to