golang 的 channel 实现 生产者/消费者 模型
发布时间:2020-12-16 18:33:47 所属栏目:大数据 来源:网络整理
导读:package mainimport ( "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 := -chan
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |