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\n", 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\n", id, <-c)
    }()

    return c
}

// end: demo2
上一篇:用redis实现TOMCAT集群下的session共享


下一篇:填坑tensorflow