golang实现生产者,消费者模型
1.借助channel实现
package main
import(
"fmt"
)
func Producer(c chan int){
defer close(c)
for i:=0;i<10;i++{
c<-i
fmt.Println("producer:",i)
}
}
func Costomer(c chan int){
hasProduct:=true
var p int
for hasProduct{
if p,hasProduct = <-c ;hasProduct{
fmt.Println("costomer get:",p)
continue
}
}
}
func main(){
c :=make(chan int)
go Producer(c)
Costomer(c)
}
2.select+channel
package main
import (
"fmt"
"sync"
"time"
)
type Product struct{
mutex sync.Mutex
product chan int
closeChan chan bool
isClosed bool
}
func Producer1(p *Product){
defer close(p.product)
for i:=0;i<10;i++{
p.product<-i
fmt.Println("producer:",i)
}
Close(p)
}
func Close(p *Product){
p.mutex.Lock()
if !p.isClosed{
close(p.closeChan)
p.isClosed = true
}
p.mutex.Unlock()
}
func Consumer1(p *Product){
var t int
timeout := make (chan bool, 1)
go func() {
time.Sleep(10e9)
timeout <- true
}()
for true{
select {
case t=<-p.product:fmt.Println("Get:",t);
case p.isClosed=<-p.closeChan:
fmt.Println("finished")
close(p.closeChan)
break
case <- timeout: fmt.Println("time out")
break;
}
if p.isClosed{
break
}
}
}
func main(){
p :=&Product{
product:make(chan int),
closeChan:make(chan bool),
}
go Producer1(p)
Consumer1(p)
}