goid

package module
v0.0.0-...-5b30f63 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 9, 2022 License: MIT Imports: 1 Imported by: 0

README

goid

Do not use this package (https://golang.org/doc/faq#no_goroutine_id).

Or use: example ./goid_example_test.go, doc https://pkg.go.dev/github.com/nikandfor/goid?tab=doc

tl;dr

func f() {
    id := goid.ID() // <-- that's why you are here

    s := goid.StartPC() // goroutine main (root) function entry point ("id := goid.ID()").
    g := goid.GoPC() // go statement pc ("go f()")
}

goroutine local storage

There is some rarely used field in goroutine struct. So it could be used to save some stuff.

type Storage struct {
    // ... any fields ...
}

func f() {
    s := (*Storage)(goid.GLoad()) // nil at first

    goid.GSave(unsafe.Pointer(&Storage{ /* ... */}))

    // ... later event in some other function ...

    s1 := (*Storage)(goid.GLoad())
    // use s1.YourField
}

One more time: it's fun, play with it, but try not to use in real code

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func GLoad

func GLoad() unsafe.Pointer

func GSave

func GSave(p unsafe.Pointer)

func GoPC

func GoPC() uintptr

GoPC returns PC of go instruction started calling goroutine

func ID

func ID() int64

ID returns calling goroutine ID

Example
package main

import (
	"fmt"
	"path"
	"runtime"

	"github.com/nikandfor/goid"
)

func main() {
	c := make(chan struct{})

	loc := func(pc uintptr) string {
		f := runtime.FuncForPC(pc)

		if f == nil {
			return ""
		}

		file, line := f.FileLine(pc)
		file = path.Base(file)

		return fmt.Sprintf("%v:%v", file, line)
	}

	f := func(c chan struct{}) {
		defer close(c)

		id := goid.ID() // this one is simple

		g := goid.GoPC()    // location of "go ...()" instruction
		s := goid.StartPC() // root (the most parent) function entry instruction of that goroutine

		n := runtime.FuncForPC(s).Name()
		n = path.Base(n)

		fmt.Printf("goroutine 0x%x  task %v (%v)  created at %v", id, loc(s), n, loc(g))
	}

	go f(c)

	<-c // wait for f to finish

	// // Output:
	// goroutine 0xc  task goid_example_test.go:19 (goid.ExampleID.func2)  created at goid_example_test.go:35
}

func StartPC

func StartPC() uintptr

StartPC returns calling goroutine start PC (function entry)

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL