The M and G of Go internals - three short questions

42 views
Skip to first unread message

Mateusz Czapliński

unread,
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

unread,
Nov 19, 2010, 7:20:23 PM11/19/10
to Mateusz Czapliński, golang-nuts
Mateusz Czapliński <czap...@gmail.com> 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
work.

Ian

fango

unread,
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.

[1] http://doc.cat-v.org/plan_9/4th_edition/papers/compiler

Cheers,
Fango

Russ Cox

unread,
Nov 22, 2010, 11:14:37 AM11/22/10
to golan...@googlegroups.com
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 
expensive.

Russ

Mateusz Czapliński

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

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