Go生产消费模式的实现

1、通道实现

import (
	"fmt"
	"math/rand"
	"time"
)

type Info interface {
	NewInfo(size int) chan interface{}
	SendInfo(ch chan<- interface{})
	GetInfo(ch <-chan interface{})
}

type Notify struct {}

func NewNotify() *Notify {
	return &Notify{}
}

func (n *Notify)NewInfo(size int) chan interface{} {
	return make(chan interface{}, size)
}

func (n *Notify)SendInfo(ch chan<- interface{})  {
	defer func() {
		if err := recover(); err != nil {
			fmt.Printf("sendinfo panic[%v]\n", err)
		}
	}()

	for  i:=0; i < 50; i++ {
		ch <- rand.Intn(100)
	}

	close(ch)
}

func (n *Notify)GetInfo(ch <-chan interface{}) {
	ticker := time.NewTicker(2*time.Second)
	for {
		select{
		case value, ok := <-ch:
			if !ok {
				ch = nil
				break
			}
			//...
			fmt.Printf("getinfo value[%v]\n", value)
		case timeout := <-ticker.C:
			fmt.Printf("getinfo timeout[%v]\n", timeout)
		}
	}
}

 

1、内存实现

import (
	"container/list"
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type Notify struct {
	data *list.List
	size int
	box  uint8          // 0代表是空的,1代表是满的
	lock *sync.RWMutex   // 代表消息上的锁
	sendCond *sync.Cond  // 代表专用于发消息的条件变量
	recvCond *sync.Cond  // 代表专用于收消息的条件变量
}

func NewNotify(size int) *Notify {
	notify := new(Notify)
	notify.size = size
	notify.data = list.New()
	notify.box = 0
	notify.lock = new(sync.RWMutex)
	notify.sendCond = sync.NewCond(notify.lock)
	notify.recvCond = sync.NewCond(notify.lock.RLocker())
	return notify
}

func (n *Notify)SendNotify()  {
	for {
		n.lock.Lock()
		for n.box == 1 {
			n.sendCond.Wait()
		}
        n.box = 1

		// 生产消息
		if n.data.Len() < n.size {
			n.data.PushBack(rand.Intn(100))
		}

		n.lock.Unlock()
		n.recvCond.Signal()    // 单发通知
		//n.recvCond.Broadcast() // 广播通知
	}
}

func (n *Notify)RecvNotify()  {
	for {
		n.lock.RLock()
		for n.box == 0 {
			n.recvCond.Wait()
		}
        n.box = 0

		// 消费消息
		if n.data.Len() > 0 {
			front := n.data.Front()
			n.data.Remove(front)
			fmt.Printf("RecvNotify = [%v]\n", front.Value)
		}

		n.lock.RUnlock()
		n.sendCond.Signal()
	}
}

 

 

以上内容仅供学习交流,在项目中根据具体需求具体分析具体实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值