Quidest?

Channels in Goroutines

ยท Lorenzo Drumond

Channels are a typed conduit (a passage, pipe) through which you can send and receive values with the channel operator <-

1ch <- v  // send v to channel ch.
2v := <- ch // receive from ch, and assign value to v.

The data flows in the direction of the arrow.

Like maps and slices, channels must be created before use:

1ch := make(chan int)

By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.

 1package main
 2
 3import "fmt"
 4
 5func sum(s []int, c chan int) {
 6  sum := 0
 7  for _, v := range s {
 8    sum += v
 9  }
10  c <- sum // send sum to c
11}
12
13func main() {
14  s := []int{7,2,8,-9,4,0}
15
16  c := make(chan int)
17  go sum(s[:len(s)/2], c)
18  go sum(s[len(s)/2:], c)
19  x, y := <-c, <-c //receive from c
20
21  fmt.Println(x, y, x+y)
22}
23
24// Output:
25// -5 17 12

References

#thread #computer_science #scheduler #process #golang #concurrency #data #channels #cpu #pcb #programming #pipe