googleio2012

channel

package main

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

func main() {
    // Unbuffered Channel of strings.
    c := make(chan string)

    go boring("boring!", c)

    for i := 0; i < 5; i++ {
        // Read From Channel - Blocking.
        fmt.Printf("You say: %q\n", <-c) // Receive expression is just a value.
    }

    fmt.Println("You're boring: I'm leaving.")
}

func boring(msg string, c chan string) {
    for i := 0; ; i++ {
        // Write to Channel.
        c <- fmt.Sprintf("%s %d", msg, i) // Expression to be sent can be any suitable value.

        // The write does not return until the read from main is complete.

        time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
    }
}

main 函数里,首先创建一个 channel 变量,channel 变量必须先创建,只申明,比如 var c chan string,会报错。
用 go 语法起一个boring function,并将 channel c 传递进去,boring function 里面往 channel c 里写入字符串,然后sleep 一段时间,main 函数里,以阻塞的方式去读取 channel c 里的内容。

generator

// Generator: Function that returns a channel
package main

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

func main() {
    c := boring("boring!") // Function returning a channel.

    for i := 0; i < 5; i++ {
        fmt.Printf("You say: %q\n", <-c)
    }

    fmt.Println("You're boring: I'm leaving.")
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}

这里拿到 channel c 的方式不是通过 make 定义,而是通过 boring function 来拿到的。boring function 里面通过 for 循环,不断的往 channel c 里塞信息。在main 函数里,有一个 for 循环 receiver 来不断的读取 channel 里的信息,然后程序就这么运行了。

/*
Generator: Function that returns a channel

The boring function returns a channel that lets us communicate with the
boring service it provides.

We can have more instances of the service.
*/
package main

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

func main() {
    joe := boring("Joe")
    ann := boring("Ann")

    for i := 0; i < 5; i++ {
        fmt.Println(<-joe) // Joe and Ann are blocking each other.
        fmt.Println(<-ann) // waiting for a message to read.
    }

    fmt.Println("You're boring: I'm leaving.")
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}

有序的 generator,相对于上一个程序,这个程序定义了两个 channel:joe 和 ann,boring 函数跟之前的没有任何区别,main 函数里,循环调用,按顺序阻塞等待一个信息去读取。

multipleplexing

/*
Multiplexing: Let whosoever is ready to talk, talk.

The fanIn function fronts the other channels. Goroutines that are ready to talk
can independently talk without Blocking the other Goroutines. The FanIn channel
receives all messages for processing.

Decouples the execution between the different Goroutines.

Joe ---
       \
        ----- FanIn --- Independent Messages Displayed
       /
Ann ---
*/
package main

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

func main() {
    c := fanIn(boring("Joe"), boring("Ann"))

    for i := 0; i < 10; i++ {
        fmt.Println(<-c) // Display any message received on the FanIn channel.
    }

    fmt.Println("You're boring: I'm leaving.")
}

func fanIn(input1, input2 <-chan string) <-chan string {
    c := make(chan string) // The FanIn channel

    go func() { // This Goroutine will receive messages from Joe.
        for {
            c <- <-input1 // Write the message to the FanIn channel, Blocking Call.
        }
    }()

    go func() { // This Goroutine will receive messages from Ann
        for {
            c <- <-input2 // Write the message to the FanIn channel, Blocking Call.
        }
    }()

    return c
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}
fanIn.png

扇入(fanIn)表示一个模块被多个模块调用。
扇出(fanOut)表示一个模块调用多个模块。
讲两个 channel 被并入一个 channel 进行输出。

sequencing

package main

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

// Message contains a channel for the reply.
type Message struct {
    str  string
    wait chan bool // Acts as a signaler
}

func main() {

    c := fanIn(boring("Joe"), boring("Ann"))

    for i := 0; i < 10; i++ {
        msg1 := <-c // Waiting on someone (Joe) to talk
        fmt.Println(msg1.str)

        msg2 := <-c // Waiting on someone (Ann) to talk
        fmt.Println(msg2.str)

        msg1.wait <- true // Joe can run again
        msg2.wait <- true // Ann can run again
    }

    fmt.Println("You're boring: I'm leaving.")
}

func fanIn(input1, input2 <-chan Message) <-chan Message {
    c := make(chan Message) // The FanIn channel.

    go func() { // This Goroutine will receive messages from Joe.
        for {
            c <- <-input1 // Write the message to the FanIn channel, Blocking Call.
        }
    }()

    go func() { // This Goroutine will receive messages from Ann.
        for {
            c <- <-input2 // Write the message to the FanIn channel, Blocking Call.
        }
    }()

    return c
}

func boring(msg string) <-chan Message { // Returns receive-only (<-) channel of strings.
    c := make(chan Message)
    waitForIt := make(chan bool) // Give main control over our execution.

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- Message{fmt.Sprintf("%s %d", msg, i), waitForIt}
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)

            <-waitForIt // Block until main tells us to go again.
        }
    }()

    return c // Return the channel to the caller.
}

fanIn 是针对 Message 的消息结构体来进行扇入的,而不是针对单独的 channel 来扇入的。

  • channel 的阻塞
    <-waitForIt

select

  • select
/*
Select is a control structure that is unique to concurrency.

The reason channels and Goroutines are built into the language.

Like a switch but each case is a communication:
-- All channels are evaluated
-- Selection blocks until one communication can proceed, which then does.
-- If multiple can proceed, select choose pseudo-randomly.
-- Default clause, if present, executes immediately if no channel is ready.

Multiplexing: Let whosoever is ready to talk, talk.

The fanIn function fronts the other channels. Goroutines that are ready to talk
can independently talk without Blocking the other Goroutines. The FanIn channel
receives all messages for processing.

Decouples the execution between the different Goroutines.

Joe ---
       \
        ----- FanIn --- Independent Messages Displayed
       /
Ann ---
*/
package main

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

func main() {
    c := fanIn(boring("Joe"), boring("Ann"))

    for i := 0; i < 10; i++ {
        fmt.Println(<-c) // Display any message received on the FanIn channel.
    }

    fmt.Println("You're boring: I'm leaving.")
}

func fanIn(input1, input2 <-chan string) <-chan string {
    c := make(chan string) // The FanIn channel

    go func() { // Now using a select and only one Goroutine
        for {
            select {
            case s := <-input1:
                c <- s

            case s := <-input2:
                c <- s
            }
        }
    }()

    return c
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}

这里把 fanIn 和 select 结合起来了,在 fanIn 里,进行 select。

  • timeout using select
/*
Timeout Using Select

The time.After function returns a channel that blocks for the specified duration.
After the interval, the channel delivers the current time, once.

The select is giving the boring routine 800ms to respond. This will be an endless
loop if boring can perform its work under 800ms every time.

*/
package main

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

func main() {
    c := boring("Joe")

    for {
        select {
        case s := <-c:
            fmt.Println(s)
        case <-time.After(800 * time.Millisecond): // This is reset on every iteration.
            fmt.Println("You're too slow.")
            return
        }
    }
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}
  • timeout using select for whole conversation
/*
Timeout Using Select

Create the timer once, outside the loop, to time out the entire conversation.
(In the previous program, we had a timeout for each message)

This time the program will terminate after 5 seconds
*/
package main

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

func main() {
    c := boring("Joe")
    timeout := time.After(5 * time.Second) // Terminate program after 5 seconds.

    for {
        select {
        case s := <-c:
            fmt.Println(s)
        case <-timeout:
            fmt.Println("You're too slow.")
            return
        }
    }
}

func boring(msg string) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            c <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
        }
    }()

    return c // Return the channel to the caller.
}

这一版本的区别与 Timeout Using Select 的是,定义了一个 timeout。
timeout := time.After(5 * time.Second)
这个 timeout 对于所有的 goroutine 是共用的。

  • Quit channel
/*
Quit Channel

You can turn this around and tell Joe to stop when we're tired of listening to him.
*/
package main

import (
    "fmt"
    "math/rand"
)

func main() {
    quit := make(chan bool)
    c := boring("Joe", quit)

    for i := rand.Intn(10); i >= 0; i-- {
        fmt.Println(<-c)
    }

    quit <- true
    fmt.Println("EXIT")
}

func boring(msg string, quit chan bool) <-chan string { // Returns receive-only (<-) channel of strings.
    c := make(chan string)

    go func() { // Launch the goroutine from inside the function. Function Literal.
        for i := 0; ; i++ {
            select {
            case c <- fmt.Sprintf("%s %d", msg, i):
                // Do Nothing
            case <-quit:
                fmt.Println("Quiting")
                return
            }
        }
    }()

    return c // Return the channel to the caller.
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,517评论 0 38
  • 异步编程对JavaScript语言太重要。Javascript语言的执行环境是“单线程”的,如果没有异步编程,根本...
    呼呼哥阅读 7,254评论 5 22
  • PythonMaO阅读 196评论 0 0
  • 说实话,在人民路时,并不是每一个包都是我做的。因为游客的需求量大,一双手撑不起一片天。那个时候还不是很喜欢做包,当...
    揭妹妹阅读 1,842评论 0 0
  • 去交让自己开心的朋友 去爱不会让自己流泪的人 去向自己想去的方向 去完成不论大小的梦想 生活应该是美好而又温柔的 ...
    LNXLNX阅读 91评论 0 0