golang如何正确关闭计时器
go如何实现并发安全的优先级队列

go实现Event事件

妙音 posted @ 2021年5月16日 21:12 in golang , 193 阅读
 

描述

 
go协程之间用通道通信,如何将它改造成事件形式。
 
 

需求描述

 
以下是我的需求
 
e := NewEvent()
//协程1等待结果, 10是等待时间
e.Wait(10)
//协程2发送结果
e.Send(xxxx)
 

原理

 
原理比较简单,不描述了
 

示例

package common

import (
	"go.uber.org/zap"
	"sync"
	"time"
)

var NOT_USED interface{} = struct{}{}

func NewEvent() *Event {
	e := &Event{
		log: zap.S(),
	}
	e.Reset()
	return e
}

type Event struct{
	waiters  sync.Map
	log *zap.SugaredLogger
}

func (e *Event) Wait(timeout time.Duration) interface{}{
	ticker := time.NewTicker(time.Second*timeout)
	defer ticker.Stop()

	resultChan := make(chan interface{}, 1)
	e.waiters.Store(resultChan, true)

	select{
	case result := <- resultChan:
		if result == NOT_USED{
			return nil
		}
		return result
	case <- ticker.C:
		close(resultChan)
	}

	e.waiters.Delete(resultChan)
	return nil
}

func (e *Event) Send(result interface{}){
	e.waiters.Range(func(k, v interface{})bool{
		resultChan := k.(chan interface{})
		select{
		case resultChan <- result:
			e.waiters.Delete(resultChan)
		default:
			e.log.Warnf("Event.Send %p resultChan=%d, result=%v", e, len(resultChan), result)
		}
		return true
	})
}

func (e *Event) Reset(){
	e.waiters.Range(func(k, v interface{})bool{
		resultChan := k.(chan interface{})
		resultChan <- NOT_USED
		e.waiters.Delete(resultChan)
		return true
	})
}
 
 
 
Avatar_small
sk 说:
2021年6月02日 04:17

Nice knowledge gaining article. This post is really the best on this valuable topic. https://www.digitekprinting.com/gator-board-posters

Avatar_small
12GB graphics card 说:
2021年6月24日 21:52

Another thing to keep in mind when choosing the right graphics card for your gaming monitor (or vice versa) is what kind of variable refresh rate technology can you take the most advantage of. For the uninitiated, variable refresh rate (VRR) technology basically syncs the number of frames shooting out of your GPU to the frame rate of your display. <a href="https://10techpro.com/best-12gb-graphics-card/">12GB graphics card</a>

Avatar_small
Digital_Work 说:
2021年7月08日 07:37

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. 123movie


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter