Golang 实例 - channel的使用

需求

协程每隔1秒, 连续3次打印 [go routine] working on it. 然后把ping通过channel通知主线程任务完成. 主线程接收到ping后, 打印 [main] All done, 然后程序退出.

这个例子演示了 go channel 的简单使用.

代码

package main

import (
    "fmt"
    "time"
)

func worker(chanWorker chan string) {

    fmt.Printf("[go routine] worker starts to work...\n")

    fmt.Printf("[go routine] working on it\n")
    time.Sleep(1 * time.Second)
    fmt.Printf("[go routine] working on it\n")
    time.Sleep(1 * time.Second)
    fmt.Printf("[go routine] working on it\n")
    time.Sleep(1 * time.Second)

    chanWorker <- "ping"

}
func main() {

    chanWorker := make(chan string)
    go worker(chanWorker)

    msgRcv := <-chanWorker
    fmt.Printf("[main] All done. Msg received:%s\n", msgRcv)
}

#learn-by-coding