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?
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.
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.
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.
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.
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.
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