| f("hello", "world") // f runs; we wait |
| |
| go f("hello", "world") // f starts running |
| g() // does not wait for f to return |
| |
| timerChan := make(chan time.Time) |
| go func() { |
| time.Sleep(deltaT) |
| timerChan <- time.Now() // send time on timerChan |
| }() |
| // Do something else; when ready, receive. |
| // Receive will block until timerChan delivers. |
| // Value sent is other goroutine's completion time. |
| completedAt := <-timerChan |
| |
| select { |
| case v := <-ch1: |
| fmt.Println("channel 1 sends", v) |
| case v := <-ch2: |
| fmt.Println("channel 2 sends", v) |
| default: // optional |
| fmt.Println("neither channel was ready") |
| } |
| |
| func Query(conns []Conn, query string) Result { |
| ch := make(chan Result, len(conns)) // buffered |
| for _, conn := range conns { |
| go func(c Conn) { |
| ch <- c.DoQuery(query): |
| }(conn) |
| } |
| return <-ch |
| } |
| |
| func XQuery(conns []Conn, query string) Result { |
| ch := make(chan Result, 1) // buffer of 1 item |
| for _, conn := range conns { |
| go func(c Conn) { |
| select { |
| case ch <- c.DoQuery(query): |
| // nothing to do |
| default: // executes if ch is blocked |
| // nothing to do |
| } |
| }(conn) |
| } |
| return <-ch |
| } |
| |
| |
| func Compose(f, g func(x float) float) |
| func(x float) float { |
| return func(x float) float { |
| return f(g(x)) |
| } |
| } |
| |
| print(Compose(sin, cos)(0.5)) |
| |
| go func() { // copy input to output |
| for val := range input { |
| output <- val |
| } |
| }() |