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()
}
}
以上内容仅供学习交流,在项目中根据具体需求具体分析具体实现。