cs_lang:go
Table of Contents
Learning Go
Simple examples
Sum the elements of a list
package main import "fmt" func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum // send sum to c } 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) x, y := <-c, <-c fmt.Println(x, y, x + y) }
Producer-consumer problem
package main import ("fmt") var done = make(chan bool) var cake = make(chan int) func produce (firstname string) { for i := 0; i < 10; i++ { fmt.Printf("%s make cake %d\n", firstname, i) cake <- i } done <- true } func consume (firstname string) { for { cake_number := <-cake fmt.Printf("%s eat cake %d\n", firstname, cake_number) } } func main () { go produce("Alice") go consume("Bob") go consume("Maxime") <- done }
Fork bomb
package main import "fmt" func main() { c := make(chan bool) go func() { count := 0 for <- c { count++ fmt.Println(count) } }() bomb(c) } func bomb(tick chan bool) { for { tick <- true go bomb(tick) } }
Books
cs_lang/go.txt · Last modified: 2014/04/18 23:19 by cedric