Is the Go map type thread safe? I have a program that has many goroutines reading and writing to a map type. If I need to implement a protection mechanism, what's the best way to do it?
+8
A:
You'd want to use goroutines and synchronize access to your maps via channels. Per the FAQ:
After long discussion it was decided that the typical use of maps did not require safe access from multiple threads, and in those cases where it did, the map was probably part of some larger data structure or computation that was already synchronized. Therefore requiring that all map operations grab a mutex would slow down most programs and add safety to few. This was not an easy decision, however, since it means uncontrolled map access can crash the program.
Jonathan Feinberg
2010-01-03 01:33:08
It is wise but they should still document and maintain which functions are thread safe. Often i run into code where in pass1 i fill a map with values and in pass2 i read it concurrently from many different threads without a single synchronization.
Lothar
2010-01-04 23:11:43