Go如何获取goroutineId

runtime包

package main

import (
    "bytes"
    "log"
    "os"
    "runtime"
    "strconv"
    "time"
)

func getGoroutineID() uint64 {
    b := make([]byte, 64)
    b = b[:runtime.Stack(b, false)]
    b = bytes.TrimPrefix(b, []byte("goroutine "))
    b = b[:bytes.IndexByte(b, ' ')]
    n, _ := strconv.ParseUint(string(b), 10, 64)
    return n
}

func logWithGoroutineID(message string) {
    gid := getGoroutineID()
    log.Printf("goroutine[%d]: %s", gid, message)
}

func main() {
    // 设置日志输出格式
    log.SetFlags(0) // 禁用时间戳,保持输出简单
    log.SetOutput(os.Stdout)

    // 在不同的 goroutine 中打印日志
    go func() {
        logWithGoroutineID("goroutine 1")
    }()

    go func() {
        logWithGoroutineID("goroutine 2")
    }()

    // 主 goroutine
    logWithGoroutineID("main goroutine")

    // 防止程序过快退出
    time.Sleep(3 * time.Second)
}

三方包 github.com/petermattis/goid

package main

import (
    "fmt"
    "log"
    "os"
    "github.com/petermattis/goid"
)

func main() {
    // 设置日志输出格式
    log.SetFlags(0) // 禁用时间戳,保持输出简单
    log.SetOutput(os.Stdout)

    // 在不同的 goroutine 中打印日志
    go func() {
        log.Printf("goroutine[%d]: goroutine 1", goid.Get())
    }()

    go func() {
        log.Printf("goroutine[%d]:  goroutine 2", goid.Get())
    }()

    // 主 goroutine
    log.Printf("goroutine[%d]: main goroutine", goid.Get())

    // 防止程序过快退出
     time.Sleep(3 * time.Second)
}

其中main goroutine打印一直都是1,其余两个是动态变化的,并不确定,类似

posted @ 2024-08-23 09:55  朝阳1  阅读(35)  评论(0)    收藏  举报