From d90145a47f4cce742bb61578d9c4fcb1b4cb088d Mon Sep 17 00:00:00 2001 From: Jack Date: Sat, 8 Aug 2020 09:42:24 +0800 Subject: [PATCH] add goroutine id retrieving feature for package gdebug --- debug/gdebug/gdebug_grid.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 debug/gdebug/gdebug_grid.go diff --git a/debug/gdebug/gdebug_grid.go b/debug/gdebug/gdebug_grid.go new file mode 100644 index 000000000..4f01fb9cd --- /dev/null +++ b/debug/gdebug/gdebug_grid.go @@ -0,0 +1,29 @@ +// Copyright 2019-2020 gf Author(https://github.com/gogf/gf). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gdebug + +import ( + "regexp" + "runtime" + "strconv" +) + +var ( + // gridRegex is the regular expression object for parsing goroutine id from stack information. + gridRegex = regexp.MustCompile(`^\w+\s+(\d+)\s+`) +) + +// GoroutineId retrieves and returns the current goroutine id from stack information. +// Be very aware that, it is with low performance as it uses runtime.Stack function. +// It is commonly used for debugging purpose. +func GoroutineId() int { + buf := make([]byte, 26) + runtime.Stack(buf, false) + match := gridRegex.FindSubmatch(buf) + id, _ := strconv.Atoi(string(match[1])) + return id +}