gid.go 699 B

12345678910111213141516171819202122232425
  1. package gls
  2. var (
  3. stackTagPool = &idPool{}
  4. )
  5. // Will return this goroutine's identifier if set. If you always need a
  6. // goroutine identifier, you should use EnsureGoroutineId which will make one
  7. // if there isn't one already.
  8. func GetGoroutineId() (gid uint, ok bool) {
  9. return readStackTag()
  10. }
  11. // Will call cb with the current goroutine identifier. If one hasn't already
  12. // been generated, one will be created and set first. The goroutine identifier
  13. // might be invalid after cb returns.
  14. func EnsureGoroutineId(cb func(gid uint)) {
  15. if gid, ok := readStackTag(); ok {
  16. cb(gid)
  17. return
  18. }
  19. gid := stackTagPool.Acquire()
  20. defer stackTagPool.Release(gid)
  21. addStackTag(gid, func() { cb(gid) })
  22. }