In Go’s GMP (goroutine, system thread, context) model, a goroutine may produce many objects and put them in P (heap memory?), will all data on P copied to G’s stack when it’s parked? If so, G’s stack may grow very large, which makes the design of P seems meaningless, but if not, how does the scheduler solve the problem that multi G’s data store in P in the same time? And it’s impossible if G wants to execute on another P.
my question is
- will all data copy to G’ stack when g is parked?
- why not just put all data on G when executing G?
There is a fundamental misunderstanding in your question:
mcache is not a placeholder for the stack, it’s a short-cut for small allocations on the heap. It holds pre-allocated blocks of memory that can be handed out to a particular goroutine, avoiding locking.
The compiler decides whether a particular variable must be allocated on the heap. Once it does, this will never be copied back to the stack.
The question is now how to allocate memory from the heap as efficiently as possible. This is where
mheap come in.
mcacheis a list of pre-allocated blocks of various sizes, with one
mcacheper processor P. Since P runs a single goroutine G at a time, allocations from
mcachedo not need to lock.
mcacheruns out of pre-allocated blocks, more are requested from
mcentralwhich is shared across Ps.
mcentralruns out, more blocks are requested from
mheapwhich may in turn request more memory from the OS.
- If the requested blocks are large enough, they are directly requested from
The point of all this is to avoid locking during small memory allocations. But all sections of memory obtained from
mheap are part of the heap, they can be used by G no matter which P it is running on, and they must be garbage collected when no longer in use.
You can find a lot more details about heap memory allocation in the following:
- Go: Memory Management and Allocation
- A visual guide to Go Memory Allocator from scratch
- Memory Management in Golang
Answered By – Marc
Answer Checked By – Jay B. (GoLangFix Admin)