From 3b54caef82f3119e6efbd642e4618cc52db8c0d2 Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Mon, 3 Sep 2012 08:37:29 -0600 Subject: [PATCH] hello world for channels --- concurrency/channels/go.go | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 concurrency/channels/go.go 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) +}