Golang runtime.Stack() function example

package runtime

Golang runtime.Stack() function usage example.

 package main

 import (
 "fmt"
 "runtime"
 )

 func echo(s string) {
 for i := 0; i < 5; i++ {
 runtime.Gosched() // see http://golang.org/pkg/runtime/#Gosched
 fmt.Println(s)
 }
 }

 func main() {

 // maximize CPU usage for multi threading
 runtime.GOMAXPROCS(runtime.NumCPU())

 buffer := make([]byte, 4096)
 buffer = buffer[:runtime.Stack(buffer, true)]

 go echo("bye") // schedule this execution on a new thread [second]

 go echo("world") // [third]

 echo("good") // current [first thread]

 fmt.Println("# go routines : ", runtime.NumGoroutine())

 fmt.Println("Stack trace bytes : ")
 fmt.Println(buffer)

 }

Reference :

http://golang.org/pkg/runtime/#Stack

Advertisement