Don't communicate by sharingmemory, sharememory by communicating.
Concurrency is not parallelism.
Channels orchestrate; mutexes serialize.
Channels
If goroutines are the activities of a concurrent Go program, channels are the connections between them.
A channel is a communication mechanism that lets one goroutine send values to another goroutine.
A channel is a reference to the data structure created by make
A channel has 2 operations, send and receive, also known as communications.
Channels in code
ch := make(chan int) // ch has type 'chan int'
ch <- x // a send statement
x = <-ch // a receive expression in an assignment statement
<-ch // a receive statement; result is discarded
close(ch) // To close a channel
Unbuffered and Buffered Channels
Channels created with simple make is called as unbuffered channel.
But make could use a second parameter which indicates the channel's capacity. If this capacity is non-zero, make will created a buffered channel.
func main() {
naturals := make(chan int)
squares := make(chan int)
// Counter
go counter(naturals)
// Squarer
go squarer(naturals, squares)
// Printer (in main goroutine)
for x := range squares {
fmt.Println(x)
}
}
Counter goroutine code
func counter(naturals chan int) {
for x := 0; x < 100; x++ {
naturals <- x
}
close(naturals)
}
Squarer goroutine code
func squarer(naturals, squares chan int) {
for x := range naturals {
squares <- x * x
}
close(squares)
}