github.com/haraldrudell/parl@v0.4.176/goid/go-id.go (about)

     1  /*
     2  © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  // Package goid obtaines a thread’s parl.ThreadID unique goroutine identifier.
     7  package goid
     8  
     9  import (
    10  	"github.com/haraldrudell/parl"
    11  	"github.com/haraldrudell/parl/pdebug"
    12  	"github.com/haraldrudell/parl/pruntime"
    13  )
    14  
    15  // GoID obtains a numeric string that as of Go1.18 is
    16  // assigned to each goroutine
    17  //   - [goid] 64-bit integer number incremented from
    18  //     1 for the main invocation thread
    19  //   - cache this value, it is expensive at 1.7 parallel mutex Lock/Unlock
    20  //     via pruntime.FirstStackLine
    21  //
    22  // Usage:
    23  //
    24  //	m := map[goid.ThreadID]SomeInterface{}
    25  //	cachedGoID := goid.GoID()
    26  //	m[cachedGoID] = …
    27  //
    28  // [goid]: https://go.googlesource.com/go/+/go1.13/src/runtime/runtime2.go#409
    29  func GoID() (threadID parl.ThreadID) {
    30  	var err error
    31  	if threadID, _, err = pdebug.ParseFirstLine(pruntime.FirstStackLine()); err != nil {
    32  		panic(err)
    33  	}
    34  	return
    35  }