分享
golang 的 channel 实现 生产者/消费者 模型
grassroots2011 · · 1773 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
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) // 主线程从信道中取数据
}转自:http://blog.csdn.net/u010020066/article/details/50516957
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1773 次点击
下一篇:把vim当做golang的IDE
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
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) // 主线程从信道中取数据
}转自:http://blog.csdn.net/u010020066/article/details/50516957