will P copy mcache to G stack when switch to new G?


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

  1. will all data copy to G’ stack when g is parked?
  2. 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 mcache, mcentral, and mheap come in.

  • mcache is a list of pre-allocated blocks of various sizes, with one mcache per processor P. Since P runs a single goroutine G at a time, allocations from mcache do not need to lock.
  • If mcache runs out of pre-allocated blocks, more are requested from mcentral which is shared across Ps.
  • If mcentral runs out, more blocks are requested from mheap which may in turn request more memory from the OS.
  • If the requested blocks are large enough, they are directly requested from mheap.

The point of all this is to avoid locking during small memory allocations. But all sections of memory obtained from mcache, mcentral and 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:

Answered By – Marc

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.