golang---channel

Posted double12gzh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang---channel相关的知识,希望对你有一定的参考价值。

0. 参考

  • https://colobu.com/2016/04/14/Golang-Channels/

1. 目录结构

jeffreyguan@jeguan ~/main$ tree                                                                                                                                                                
.
├── channel
│?? └── woker.go
├── go.mod
└── main.go

1 directory, 3 files

2. main.go

package main

import (
    "fmt"
    "main/channel"
)

func main() {
    fmt.Println("Begin...")
    // demo1
    //channel.ChanDemo()

    //  demo2
    channel.ChanDemo2()
}

3. channel.go

package channel

import (
    "fmt"
    "time"
)

// begin: demo1
func ChanDemo() {
    var channels [10]chan int

    for i := 0; i < 10; i++ {
        channels[i] = make(chan int)

        go Worker(i, channels[i])
    }

    for i, c := range channels {
        c <- 'a' + i
    }

    time.Sleep(time.Minute)
}

func Worker(id int, c chan int) {
    for {
        fmt.Printf("Worker %d received %d
", id, <-c)
    }
}

// end: demo1

// begin: demo2
func ChanDemo2() {
    var channels [10]chan<- int

    for i := 0; i < 10; i++ {
        channels[i] = CreateWorker(i)
    }

    for i, c := range channels {
        c <- 'a' + i
    }

    time.Sleep(time.Minute)
}

func CreateWorker(id int) chan<- int {
    c := make(chan int)

    go func() {
        fmt.Printf("Worker %d received %c
", id, <-c)
    }()

    return c
}

// end: demo2

4. 同步

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Begin...")

    Done := make(chan bool, 1)
    go SyncWorker(Done)
    <-Done
}

func SyncWorker(done chan<- bool) {
    time.Sleep(time.Second * 2)

    done <- true
}

以上是关于golang---channel的主要内容,如果未能解决你的问题,请参考以下文章

golang:channel消息传递练习

golang channel本质——共享内存

golang - channel

golang channel 超时如何处理

golang channel tips

Golang channel源码分析