golang生产者消费者模型示例代码

`package main

import (
"fmt"
"strconv"
"time"
)

//生产者结构体
type Productor struct {
Name string
}
var Chquit = make(chan interface{}, 2)
var Bag = false
func main() {
fmt.Println("这是一个生产者消费者模型的示例")
Chscz := make(chan Productor, 5)
Chwl := make(chan Productor,5)
go scz(Chscz)
go wl(Chscz,Chwl)
go xfz(Chwl)
go monitor()
<-Chquit
fmt.Println("主协程挂了")
}

// 生产者
func scz(Chscz chan Productor) {
for{
pro := Productor {"商品" + strconv.Itoa(time.Now().Second())}
fmt.Println("生产了商品" + pro.Name)
if Bag {
fmt.Println("给主协程的退出管道写入任意字符,让主协程结束运行")
Chquit<-"Go Die"
}
time.Sleep(time.Second)
Chscz<-pro
}

}

func wl(Chscz chan Productor,Chwl chan Productor) {
for {
pro := <- Chscz
Chwl <-pro
fmt.Println("搬用了商品" + pro.Name )
}
}

func xfz(Chwl chan Productor) {
for{
pro := <-Chwl
fmt.Println("消费了商品" + pro.Name)
}

}

func monitor() {
for{
sec := time.Now().Second()
fmt.Println("当前秒数是:",sec)
time.Sleep(time.Second)
if sec == 0 {
Bag = true
return
}

}

}`

相关推荐