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?
It's important to note that maps in go are not safe for concurrent use. Maps are not safe for concurrent use: it's not defined what happens when you read and write to them simultaneously.
With Go, it's possible to do multi-threaded concurrency and parallelization with goroutines and goroutines work in an asynchronous way hence making use of both multi-threading and asynchronous programming efficiently.
Goroutine does not have ID because go does not have Thread Local Storage. Threads have their own unique ID because they have Thread Local Storage. Goroutines are cheaper than threads.
No. Goroutine methods are managed by golang runtime. Thread are managed by operating systems. Goroutine are independent to hardware.
You'd want to use goroutines and synchronize access to your maps via channels. Explanation from 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.
The language does not preclude atomic map updates. When required, such as when hosting an untrusted program, the implementation could interlock map access.
Since Go 1.9 the best way is to use sync.Map type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With