Saturday, September 9, 2017

Why is a Goroutine’s stack infinite high cpu spikes:

Why is a Goroutine’s stack infinite high cpu spikes:

Empty loop:

for{
}

uses 100% of a CPU Core.

The proper way to wait for some operation depending to the use case you may use:

- sync.WaitGroup like this
- select {}
- channels
- time.Sleep
- time.After

One of the key features of Goroutines is their cost; they are cheap to create in terms of initial memory footprint (as opposed to the 1 to 8 megabytes with a traditional POSIX thread) and their stack grows and shrinks as necessary. This allows a Goroutine to start with a single 4096 byte stack which grows and shrinks as needed without the risk of ever running out.
There is however one detail I have withheld until now, which links the accidental use of a recursive function to a serious case of memory exhaustion for your operating system, and that is, when new stack pages are needed, they are allocated from the heap.
As your infinite function continues to call itself, new stack pages are allocated from the heap, permitting the function to continue to call itself over and over again. Fairly quickly the size of the heap will exceed the amount of free physical memory in your machine, at which point swapping will soon make your machine unusable.
The size of the heap available to Go programs depends on a lot of things, including the architecture of your CPU and your operating system, but it generally represents an amount of memory that exceeds the physical memory of your machine, so your machine is likely to swap heavily before your program ever exhausts its heap.

Reference:

https://stackoverflow.com/questions/39493692/difference-between-the-main-goroutine-and-spawned-goroutines-of-a-go-program

http://dave.cheney.net/2013/06/02/why-is-a-goroutines-stack-infinite

No comments: