golang生产者消费者

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)
}

// channel关闭多次,或者使用已关闭的channel会引起panic,这里使用了锁来安全地关闭channel
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) // sleep one second
		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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值