ITPub博客

首页 > 应用开发 > Go语言 > golang协程学习--协程与管道配合的简单案例

golang协程学习--协程与管道配合的简单案例

原创 Go语言 作者:lsq_008 时间:2022-10-12 09:09:03 0 删除 编辑

package main


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

type Cat struct {
    Name string
    Age   int
}

func writeCh(ch chan interface{}) {
    for i := 0; i < 10; i++ {
        time. Sleep(time.Second)
        cat := Cat{Name: randomString( 5), Age: 10}
        ch <- cat
        fmt. Printf( " %d 进入管道 \n ", i)
    }
    close(ch)
}

func readChan(ch chan interface{}, done chan bool) {
    for {
        v, ok := <-ch
        if !ok {
            break
        }
        fmt. Println( "读协程读入,", v)
    }
    // for v := range ch {
    //  fmt.Println(v)
    // }
    done <- true
    // close(done)
}

func randomString(length int) string {
    rand. Seed(time. Now(). UnixNano())
    b := make([] byte, length)
    rand. Read(b)
    return fmt. Sprintf( " %x ", b)[:length]
}

func main() {
    catChan := make( chan interface{}, 10)
    done := make( chan bool)

    go writeCh(catChan)
    go readChan(catChan, done)

    <-done

}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10972173/viewspace-2917885/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
十余年大型金融及电信系统数据库管理经验,曾服务于中国建设银行、中国移动。对oracle,mysql数据库有深入了解。 擅长python开发,独立开发了开源数据库自动化监控运维平台Power Monitor。

注册时间:2008-02-29

  • 博文量
    335
  • 访问量
    1369108