Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the go map structure thread-safe?

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?

like image 336
marketer Avatar asked Jan 03 '10 01:01

marketer


People also ask

Is map in Go thread-safe?

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.

Is Go good for multithreading?

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.

Are there threads in Go?

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.

Is Go routine the same as thread?

No. Goroutine methods are managed by golang runtime. Thread are managed by operating systems. Goroutine are independent to hardware.


2 Answers

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.

like image 140
Jonathan Feinberg Avatar answered Sep 21 '22 11:09

Jonathan Feinberg


Since Go 1.9 the best way is to use sync.Map type.

like image 21
Grzegorz Żur Avatar answered Sep 25 '22 11:09

Grzegorz Żur