diff --git a/buffered-channels.go b/buffered-channels.go new file mode 100644 index 0000000..5b82ddf --- /dev/null +++ b/buffered-channels.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + ch := make(chan int, 2) + ch <- 1 + ch <- 2 + fmt.Println(<-ch) + fmt.Println(<-ch) +} diff --git a/channels.go b/channels.go new file mode 100644 index 0000000..690dfb9 --- /dev/null +++ b/channels.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func sum(s []int, c chan int) { + sum := 0 + for _, v := range s { + sum += v + } + c <- sum // send sum to c +} + +func main() { + s := []int{7, 2, 8, -9, 4, 0} + c := make(chan int) + go sum(s[:len(s) / 2], c) + go sum(s[len(s) / 2:], c) + x, y := <-c, <-c // receive from c + + fmt.Println(x, y, x + y) +} diff --git a/default-selection.go b/default-selection.go new file mode 100644 index 0000000..1924fac --- /dev/null +++ b/default-selection.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + tick := time.Tick(100 * time.Millisecond) + boom := time.After(500 * time.Millisecond) + for { + select { + case <-tick: + fmt.Println("tick.") + case <-boom: + fmt.Println("BOOM!") + return + default: + fmt.Println(" .") + time.Sleep(50 * time.Millisecond) + } + } +} diff --git a/goroutines.go b/goroutines.go new file mode 100644 index 0000000..84bf43c --- /dev/null +++ b/goroutines.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "time" +) + +func say(s string) { + for i := 0; i < 5; i++ { + time.Sleep(100 * time.Millisecond) + fmt.Println(s) + } +} + +func main() { + go say("world") + say("hello") +} diff --git a/range-and-close.go b/range-and-close.go new file mode 100644 index 0000000..8d930ed --- /dev/null +++ b/range-and-close.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" +) + +func fibonacci(n int, c chan int) { + x, y := 0, 1 + for i := 0; i < n; i++ { + c <- x + x, y = y, x + y + } + close(c) +} + +func main() { + c := make(chan int, 10) + go fibonacci(cap(c), c) + for i := range c { + fmt.Println(i) + } +} diff --git a/select.go b/select.go new file mode 100644 index 0000000..035d847 --- /dev/null +++ b/select.go @@ -0,0 +1,28 @@ +package main + +import "fmt" + +func fibonacci(c, quit chan int) { + x, y := 0, 1 + for { + select { + case c <- x: + x, y = y, x+y + case <-quit: + fmt.Println("quit") + return + } + } +} + +func main() { + c := make(chan int) + quit := make(chan int) + go func() { + for i := 0; i < 10; i++ { + fmt.Println(<-c) + } + quit <- 0 + }() + fibonacci(c, quit) +}