1
0
Fork 0

hello world for channels

This commit is contained in:
Stephen M. McQuay 2012-09-03 08:37:29 -06:00
parent c45dcc9178
commit 3b54caef82
1 changed files with 41 additions and 0 deletions

View File

@ -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)
}