A question about channel

110 views
Skip to first unread message

LinkinStar

unread,
Sep 14, 2021, 12:30:14 PM9/14/21
to golang-nuts
Hi golang-nuts,
When I read the source code about chan.go, I found some problems that were a little difficult to understand.

hchan has two function, full and empty.

func full(c *hchan) bool {
// c.dataqsiz is immutable (never written after the channel is created)
// so it is safe to read at any time during channel operation.
if c.dataqsiz == 0 {
// Assumes that a pointer read is relaxed-atomic.
return c.recvq.first == nil
}
// Assumes that a uint read is relaxed-atomic.
return c.qcount == c.dataqsiz
}



func empty(c *hchan) bool {
// c.dataqsiz is immutable.
if c.dataqsiz == 0 {
return atomic.Loadp(unsafe.Pointer(&c.sendq.first)) == nil
}
return atomic.Loaduint(&c.qcount) == 0
}



why does the empty function use atomic while the full function does not?


Thank you in advance for your read and help.

Ian Lance Taylor

unread,
Sep 14, 2021, 2:00:09 PM9/14/21
to LinkinStar, golang-nuts
See the lengthy comment above the only call of full, which explains
why it's OK to reorder the memory loads.

Ian
Reply all
Reply to author
Forward
0 new messages