The M and G of Go internals - three short questions

Skip to first unread message

Mateusz Czapliński

Nov 19, 2010, 7:03:32 PM11/19/10
to golang-nuts
Am I right if I assume that the cryptic "M" and "G" in Go internals
are used as shorthands for, respectively, word "thread" and word
"goroutine"? If so, then is the global "m" simply a container of some
data local to the current thread? and finally, could I ask what the
global "g" is, as (if the above are right) m->curg is apparently "the
currently running goroutine in the current thread"?

Thanks in advance
Mateusz Czapliński

Ian Lance Taylor

Nov 19, 2010, 7:20:23 PM11/19/10
to Mateusz Czapliński, golang-nuts
Mateusz Czapliński <> writes:

They are both local to the current OS thread. As you say, m is
associated with the OS thread and g is associated with the goroutine. I
admit that I don't know why the global variable g exists; as you say, it
could be retrieved from the m structure with only minor loss of
efficiency. At least, I don't know of any cases where that would not



Nov 19, 2010, 7:51:32 PM11/19/10
to golang-nuts
Maybe it's just for historical reason. In plan9 C compiler [1], they
are external registers.



Russ Cox

Nov 22, 2010, 11:14:37 AM11/22/10
m is the current OS thread (m stands for machine;
in the Plan 9 kernel it was the variable name for the
current processor's Mach structure), like u in the 
original Unix kernel.

g is usually the current goroutine, but it's real purpose
is to be the definitive place to find the current stack
bounds during the stack growth check at the beginning
of most functions.

m->curg is often == g, but not always.  When
the stack is out of space and needs to be grown,
the code switches to g == m->g0 in order to have
some stack in which to work, and then it switches
back to m->curg when done.

It would be possible to introduce another field in m
instead of having the separate g, but that would
require another memory reference in each function
prologue, and the single word of memory is not 


Mateusz Czapliński

Nov 23, 2010, 3:11:50 AM11/23/10
to golang-nuts
Some leisure-time reading is going to be a bit easier now, at least
for me :)

Mateusz Czapliński
Reply all
Reply to author
0 new messages