首页 > 其他 > 详细

golang 的 channel 实现 生产者/消费者 模型

时间:2020-03-04 14:03:35      阅读:74      评论:0      收藏:0      [点我收藏+]
package main

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

func productor(channel chan<- string) {
    for {
        channel <- fmt.Sprintf("%v", rand.Float64())
        time.Sleep(time.Second * time.Duration(1))
    }
}

func customer(channel <-chan string) {
    for {
        message := <-channel // 此处会阻塞, 如果信道中没有数据的话
        fmt.Println(message)
    }
}

func main() {
    channel := make(chan string, 5) // 定义带有5个缓冲区的信道(当然可以是其他数字)
    go productor(channel) // 将 productor 函数交给协程处理, 产生的结果传入信道中
    customer(channel) // 主线程从信道中取数据
}

 

golang 的 channel 实现 生产者/消费者 模型

原文:https://www.cnblogs.com/ExMan/p/12408667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!