Fragment Description:



Simplest and most direct channel usage:
Start 4 goroutines, give each one a word.
Each sleeps, then returns the word on a channel.
The main goroutine prints words as they return.
The print loop represents a checkpoint:
main doesn't exit until all words have returned and been printed.


channelBasicPattern

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:27

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    q := make(chan string)
    words := []string{"Enjoy", "Go", "Coding", "Patrick"}
    t := time.Now()
    for _, w := range words {
        // passing w to each goroutine to avoid repeating the same! Try not to.
        go func(w string) {
            time.Sleep(time.Duration(rand.Int63n(1e9)))
            q <- w
        }(w)
    }
    for i := 0; i < len(words); i++ {
        // reading from channel q
        fmt.Printf("%q\t\t", <-q)
        fmt.Println("Created in:", time.Now().Sub(t))
    }
}

/*  Expected Output
"Go"     Created in: 80.0046ms
"Patrick"    Created in: 114.0066ms
"Enjoy"      Created in: 739.0423ms
"Coding" Created in: 881.0504ms
*/



Comments