Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Go have something like ThreadLocal from Java?

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?

like image 593
modkzs Avatar asked Aug 11 '15 03:08

modkzs


People also ask

What is ThreadLocal in Java?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

When should I use ThreadLocal?

ThreadLocal is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime. As an example, imagine a web application, where each request is served by a different thread.

How is ThreadLocal implemented?

The implementation of ThreadLocalMap is not a WeakHashMap , but it follows the same basic contract, including holding its keys by weak reference. Essentially, use a map in this Thread to hold all our ThreadLocal objects.

What is the purpose of declaring a variable of type ThreadLocal?

It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.


1 Answers

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.

like image 150
Bayta Darell Avatar answered Oct 22 '22 13:10

Bayta Darell