go 并发练习(发布订阅模型)

go 并发练习(发布订阅模型)

还是直接上代码

原型见《GO高级编程》柴树杉 曹春晖著(1.6)

package main
import 
(
	"fmt"
	"time"
	"sync"
)

type (
	subcriber chan interface{}
	topicFunc func(v interface{}) bool
)
// 发布者结构体
type Publisher struct {
	m sync.RWMutex                        //增加订阅者,线程间互斥
	buffer int32                          //订阅者信道缓冲
	timeout time.Duration                 //等待超时,当订阅者信道缓冲满后超时
	subscribers map[subcriber]topicFunc   //存储订阅者,和订阅者的过滤函数
}
// 构建一个发布者
func NewPiblisher(publishTimeout time.Duration, buffer int32) *Publisher{
	return &Publisher{
		buffer: buffer,
		timeout: publishTimeout,
		subscribers: make(map[subcriber]topicFunc),
	}
}
// 订阅全部信息
func (p *Publisher) Subscribe() subcriber{
	return p.SubscribeTopic(nil)
}
// 订阅信息,按着入参过滤
func (p *Publisher) SubscribeTopic(topic topicFunc) subcriber{
	ch := make(subcriber, p.buffer)
	p.m.Lock()
	defer p.m.Unlock()
	
	p.subscribers[ch] = topic
	return ch
}
// 某一个订阅者退出
func (p *Publisher) SubQuit(sub subcriber) {
	p.m.Lock()
	defer p.m.Unlock()
	delete(p.subscribers, sub)
	close(sub)
}
// 发布信息
func (p *Publisher) Publish(v interface{}) {
	p.m.RLock()
	defer p.m.RUnlock()
	
	var wg sync.WaitGroup
	for sub, topic := range p.subscribers {
		wg.Add(1)
		go func(sub subcriber, ftopic topicFunc){
			defer wg.Done()
			if topic!=nil && !topic(v) {
				return
			}
			select {
				case sub<-v:
				case <-time.After(p.timeout):
					fmt.Println("订阅者么有取数据导致信道堵塞...")
			}
		}(sub, topic)
	}
	wg.Wait()
}

func main(){
	p := NewPiblisher(time.Second, 2)
	all := p.Subscribe()
	str := p.SubscribeTopic(func(v interface{}) bool{
		if _,ok := v.(string); ok {
			return true
		}
		return false
	})
	p.Publish("hello")
	p.Publish("hello")
	p.Publish("hello")
	go func(){
		for msg:= range all{
			fmt.Println("all: ",msg)
		}
	}()
	go func(){
		for msg:= range str{
			fmt.Println("str: ",msg)
		}
	}()
	time.Sleep(10* time.Second)
	fmt.Println("hello world")
	
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值