golang并发编程

以推送文章为例,推送给谁?推送什么?先准备好,整合成以下结构:

type PushUser struct {
    Uid       string //推送人
    ArticleId string //推送文章id
    PushType  string //推送类型
}

然后起一个goroutine把推送信息写入通道,起n个goroutine读通道,n依赖用户数

架构如下:

golang并发编程_第1张图片

写入通道代码如下:

wg := &sync.WaitGroup{}
	wg.Add(1)
	go func() {
		for _, u := range users {
			if chapterPushInfo, ok := chapterPushMap[u.Uid]; ok {
				chPushUser <- core.PushUser{Uid: u.Guid, ArticleId: chapterPushInfo.BookId, PushType: PushTypeBook}
			}
		}
		wg.Done()
		close(chPushUser) //写完了,一定要close,不然读通道地方会阻塞
		log.Info("add push user to channel finished")
	}()

从通道读:

wg.Add(1)
	go func() {
		now := time.Now().Add(5 * time.Minute)
		pushTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), 0, 0, now.Location())
		pushTimeStr := pushTime.Format("20060102150405000000")
		core.RunPush(chPushUser, chAddFreq, goroutineNum, pushTimeStr, 1, PushTypeChapter)
		wg.Done()
		close(chAddFreq)
		log.Info("push finished")
	}()

golang并发编程_第2张图片

 

你可能感兴趣的:(goLang,goroutine,并发)