Synchronized goroutines (part II)

Channel communication

Michał Łowicki
Nov 14, 2016 · 3 min read

Sending to a channel happens before receiving sent value.

Thanks to that we can order operations spread across two goroutines:

var v int
var wg sync.WaitGroup
wg.Add(2)
ch := make(chan int)
go func() {
v = 1
ch <- 1
wg.Done()
}()
go func() {
<-ch
fmt.Println(v)
wg.Done()
}()
wg.Wait()

send ↔ receive

var v, w int
var wg sync.WaitGroup
wg.Add(2)
ch := make(chan int)
go func() {
v = 1
ch <- 1
fmt.Println(w)
wg.Done()
}()
go func() {
w = 2
<-ch
fmt.Println(v)
wg.Done()
}()
wg.Wait()
go func() {
v = 1
<-ch
wg.Done()
}()
go func() {
ch <- 1
fmt.Println(v)
wg.Done()
}()

Channel closing

ch := make(chan int)
close(ch)
fmt.Println(<-ch) // prints 0

Closing channel happens before receiving zero value from closed channel

It can be used to solve our initial problem just by replacing send operation with call of built-in close:

go func() {
v = 1
close(ch)
wg.Done()
}()
go func() {
<-ch
fmt.Println(v)
wg.Done()
}()

Buffered channels

So far we’ve talked about unbuffered channels. Buffered channels don’t block on send when buffer is not full and do not block on receiving when buffer is not empty:

ch := make(chan int, 1)
ch <- 1
fmt.Println(<-ch)

The kth receive on a channel with capacity c happens before the (k+c)th send from that channel completes.

Suppose capacity is set to 3. First 3 operations of sending value over a channel can return without accompanying receive statement. But in order to 4th send to complete at least one receive would need to be done.

var v int
var wg sync.WaitGroup
wg.Add(2)
ch := make(chan int, 3)
go func() {
v = 1
<-ch
wg.Done()
}()
go func() {
ch <- 1
ch <- 1
ch <- 1
ch <- 1
fmt.Println(v)
wg.Done()
}()
wg.Wait()

golangspec

A series dedicated to deeply understand Go’s specification and language’s nuances

Michał Łowicki

Written by

Software engineering manager at Facebook, previously Opera, never satisfied.

golangspec

A series dedicated to deeply understand Go’s specification and language’s nuances