In Java the thread executing the code can access current thread object using a static method Thread.currentThread(). This object has id, name etc.
Is there an equivalent construct that can be used from within a goroutine?
In Java the thread executing the code can access current thread object using a static method Thread.currentThread(). This object has id, name etc.
Is there an equivalent construct that can be used from within a goroutine?
No. It is technically possible to access it with assembly language or cgo, but you should not; it’s considered bad design in Go. For example, see the documentation to this package that can do it for you:
package id gives you access to the goroutine id. If you use this package, you will go straight to hell.
Whatever you’re trying to do with a goroutine ID should be done some other way. Some common scenarios are:
Logging: Generate your own *Request
or requestID
and pass it around explicitly or in a context.Context
and pass that Context
around explicitly. Don’t use the goroutine ID.
“goroutine local storage” (as opposed to thread local storage in other languages). Again, you should either pass cached data around explicitly (or via a Context
) or maybe use a sync.Pool
, etc. Do not hack together something that uses the goroutine ID.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.