Goroutines and channels
Concurrency is a program's ability to deal with several tasks at once: serving a thousand clients, downloading several files, processing data while waiting for a network response. It is the feature for which many people choose Go. It is based on two simple pieces: goroutines, which are lightweight tasks, and channels, which are pipes through which goroutines send data to each other. The language's philosophy is summed up like this: do not communicate by sharing memory; share memory by communicating.
Goroutines
A goroutine is a function that runs concurrently. It is launched by writing go in front of a call: go work(). They are very cheap: they take a few kilobytes and you can have hundreds of thousands. The Go runtime distributes them among the processor cores. But there is a classic trap: when main ends, the program ends and kills all goroutines, even if they have not finished. That is why a mechanism is needed to wait for them; channels and the WaitGroup we will see in the next lesson serve for that. Using time.Sleep to wait is just a crutch for examples.
Channels
A channel is created with make(chan T), where T is the type of the values that travel. You send with ch <- value and receive with value := <-ch. On an unbuffered channel, the send blocks until someone receives, and the receive blocks until someone sends; that synchronization is what makes the model so safe. With a buffer, make(chan T, n), the send only blocks when the buffer is full. Whoever finishes sending closes the channel with close(ch); receiving from a closed one returns the pending values and then the zero value, and for range over a channel receives until it is closed. Only the sender should close, never the receiver, and sending to a closed channel causes a panic.
package main
import "fmt"
func square(n int, out chan<- int) {
out <- n * n // send the result
}
func main() {
results := make(chan int)
for i := 1; i <= 3; i++ {
go square(i, results) // three concurrent goroutines
}
sum := 0
for i := 0; i < 3; i++ {
sum += <-results // receive blocks until a value arrives
}
fmt.Println(sum) // 14 (1+4+9), order of arrival does not matter
}package main
import "fmt"
// producer sends numbers and closes the channel when done
func producer(n int) <-chan int {
ch := make(chan int)
go func() {
defer close(ch)
for i := 1; i <= n; i++ {
ch <- i
}
}()
return ch
}
func main() {
for v := range producer(5) { // ends when the channel is closed
fmt.Print(v, " ")
}
fmt.Println()
buffered := make(chan string, 2)
buffered <- "a"
buffered <- "b" // does not block: buffer has room
first, second := <-buffered, <-buffered
fmt.Println(first, second, len(buffered)) // a b 0
}Common mistakes
The first is deadlock: if all goroutines are blocked waiting, for example sending on an unbuffered channel with nobody receiving, Go detects the situation and ends with the message all goroutines are asleep. The second is goroutine leaks: a goroutine that waits forever for a value that will never arrive stays alive consuming memory. The third is forgetting to close the channel when the receiver uses for range: the loop never ends. The directional types chan<- T (send only) and <-chan T (receive only) in function parameters document the intention and the compiler prevents wrong uses.
- go f() launches a goroutine; main does not wait for them.
- make(chan T) unbuffered synchronizes; make(chan T, n) is buffered.
- ch <- v sends; v := <-ch receives; close(ch) closes.
- for v := range ch receives until it is closed.
- Only the sender closes the channel.
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف