Search code examples
gogoroutine

How to identify the stack size of goroutine?


I know go routine can have a few blocking actions, wonder if a goroutine can call a user-defined blocking function like a regular function. A user-defined blocking function has a few steps like, step1, step2.

In another word, I would like to find out whether we can have nested blocking calls in a go routine.

UPDATE:

Original intention was to find the stack size used by goroutine, especially with nested blocking calls. Sorry for the confusion. Thanks to the answer and comments, I created the following function that has 100,000 goroutines, it took 782MB of virtual memory and 416MB of Resident memory on my Ubuntu desktop. It evens out to be 78KB of memory for each go routine stack. Is this a correct statement?

package main

import (
    "fmt"
    "time"
)

func f(a int) {
    x := f1(a);
    f2(x);
}
func f1(a int) int {
    r := step("1a", a);
    r = step("1b", r);
    return 1000 * a;
}
func f2(a int) {
    r := step("2a", a);
    r = step("2b", r);
}
func step(a string, b int) int{
    fmt.Printf("%s %d\n", a, b);
    time.Sleep(1000 * time.Second)
    return 10 * b;
}

func main() {
    for i := 0; i < 100000; i++ {
        go f(i);
    }
    //go f(20);
    time.Sleep(1000 * time.Second)
}

Solution

  • I believe you're right, though I'm unsure of the relationship between "virtual" and "resident" memory it's possible there's some overlap.

    Some things to consider: you're running 100,000 it appears, not 10,000.

    The stack itself might contain things like the strings used for the printfs, method parameters, etc.

    As of go 1.2 the default stack size (per go routine) is 8KB which may explain some of it.

    As of go 1.3 it also uses an exponentially increasing stack size, but I doubt that's the problem you're running into.