diff --git a/concurrency/channels/go.go b/concurrency/channels/go.go new file mode 100644 index 0000000..38da1ed --- /dev/null +++ b/concurrency/channels/go.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" +) + +func sum(a []int, c chan int) { + s := 0 + for _, v := range a { + s += v + } + c <- s +} + +func main() { + a := []int{7, 2, 8, -9, 4, 0} + c := make(chan int) + go sum(a[:len(a)/2], c) + go sum(a[len(a)/2:], c) + go sum(a, c) + x, y, z := <-c, <-c, <-c + fmt.Printf("%d %d %d\n", x, y, z) + + // panics with deadlock if buffer doesn't match reads from chan + // throw: all goroutines are asleep - deadlock! + c2 := make(chan int, 2) + c2 <- 1 + c2 <- 2 + // must not do this without increasing buffer size: c2 <- 2 + fmt.Println(<-c2) + fmt.Println(<-c2) + + // note that this chanel is buffered, and that we don't need to launch go + // routines + c_buffered := make(chan int, 10) + sum(a[:len(a)/2], c_buffered) + sum(a[len(a)/2:], c_buffered) + sum(a, c_buffered) + x, y, z = <-c_buffered, <-c_buffered, <-c_buffered + fmt.Printf("%d %d %d\n", x, y, z) +}