Does Go have something like ThreadLocal from Java?

modkzs picture modkzs · Aug 11, 2015 · Viewed 10.4k times · Source

I use Go and Gin to setup my website and want to know the database access time. I use goroutine so if don't use something like thread-local, I must change almost every function to do it. Does Go have a good way to do it?

Answer

Cerise Limón picture Cerise Limón · Aug 11, 2015

The Go runtime and standard libraries do not provide goroutine local storage or a goroutine identifier that can be used to implement goroutine local storage.

The third party gls package implements goroutine local storage in an interesting way. Some find this package horrifying and others think it's clever.

The Go team recommends passing context explicitly as function argument instead of using goroutine local storage. See the context blog post and package documentation for more information.