Fragment Description:



A Rob Pike example about Channel Generator idiom.
Concurrency is the key to designing high performance network services.
Go's concurrency primitives (goroutines and channels) provide a simple a nd efficient means of expressing concurrent execution.
In this talk we see how tricky concurrency problems can be solved gracefully with simple Go code.
Watch, 15mn49 :
https://www.youtube.com/watch?v=f6kdp27TYZs


channelGenerator

Go Playground

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

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

package main

import (
    "fmt"
    "time"
)

func channelGenerator(msg string) <-chan string { //return a receive-only channel of strings.
    c := make(chan string)
    go func() { //we launch the goroutine from inside the generator function
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg+" Chums...? ", i)
            time.Sleep(time.Duration(0.02*1e3) * time.Millisecond)
        }
    }()
    return c //return c to the caller
}
func main() {
    returnedChannel := channelGenerator("boring, isn't it, ") //function returning a channel
    joe := channelGenerator("is it Joe,")
    ann := channelGenerator("is it Ann,")
    for i := 0; i < 5; i++ {
        fmt.Printf("You say %q\n", <-returnedChannel)
        fmt.Printf("You say %q\n", <-joe)
        fmt.Printf("You say %q\n", <-ann)
    }
    fmt.Printf("You are too boring, I'm leaving!...\n")
}

/* Expected Output:
You say "boring, isn't it,  Chums...?  0"
You say "is it Joe, Chums...?  0"
You say "is it Ann, Chums...?  0"
You say "boring, isn't it,  Chums...?  1"
You say "is it Joe, Chums...?  1"
You say "is it Ann, Chums...?  1"
You say "boring, isn't it,  Chums...?  2"
You say "is it Joe, Chums...?  2"
You say "is it Ann, Chums...?  2"
You say "boring, isn't it,  Chums...?  3"
You say "is it Joe, Chums...?  3"
You say "is it Ann, Chums...?  3"
You say "boring, isn't it,  Chums...?  4"
You say "is it Joe, Chums...?  4"
You say "is it Ann, Chums...?  4"
You are too boring, I'm leaving!..
*/



Comments