multithreadinggogoroutinethread-local-storagemdc

Global Thread-local Storage feasibility and best Practices in Go


I am a beginner in Golang, and I would like to implement something similar to the Mapped Diagnostic Context (MDC) in Java, which is achieved through thread-local storage, in Go. However, I find it hard to find information about global thread-local storage in Go online.

I have several questions:

I've found some references to this, but I can't come to a conclusion to decide whether to implement it or not.


Solution

  • There are several issues here, which usually happen when you try to emulate features of other languages in Go.

    func f() {
       var i int
       go func() {
          // Here, use i as thread-local storage
       }()
    }
    
    func f() {
      go func() {
         var t threadLocalData
         ...
         g(t)
         ...
      }{}
    }