1 Star 1 Fork 0

hh/etcd

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
event_dispatcher.go 1.73 KB
一键复制 编辑 原始数据 按行查看 历史
Ben Johnson 提交于 2014-03-24 15:09 . bump(github.com/goraft/raft): 6bf34b9
package raft
import (
"reflect"
"sync"
)
// eventDispatcher is responsible for managing listeners for named events
// and dispatching event notifications to those listeners.
type eventDispatcher struct {
sync.RWMutex
source interface{}
listeners map[string]eventListeners
}
// EventListener is a function that can receive event notifications.
type EventListener func(Event)
// EventListeners represents a collection of individual listeners.
type eventListeners []EventListener
// newEventDispatcher creates a new eventDispatcher instance.
func newEventDispatcher(source interface{}) *eventDispatcher {
return &eventDispatcher{
source: source,
listeners: make(map[string]eventListeners),
}
}
// AddEventListener adds a listener function for a given event type.
func (d *eventDispatcher) AddEventListener(typ string, listener EventListener) {
d.Lock()
defer d.Unlock()
d.listeners[typ] = append(d.listeners[typ], listener)
}
// RemoveEventListener removes a listener function for a given event type.
func (d *eventDispatcher) RemoveEventListener(typ string, listener EventListener) {
d.Lock()
defer d.Unlock()
// Grab a reference to the function pointer once.
ptr := reflect.ValueOf(listener).Pointer()
// Find listener by pointer and remove it.
listeners := d.listeners[typ]
for i, l := range listeners {
if reflect.ValueOf(l).Pointer() == ptr {
d.listeners[typ] = append(listeners[:i], listeners[i+1:]...)
}
}
}
// DispatchEvent dispatches an event.
func (d *eventDispatcher) DispatchEvent(e Event) {
d.RLock()
defer d.RUnlock()
// Automatically set the event source.
if e, ok := e.(*event); ok {
e.source = d.source
}
// Dispatch the event to all listeners.
for _, l := range d.listeners[e.Type()] {
l(e)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/w1229748769/etcd.git
git@gitee.com:w1229748769/etcd.git
w1229748769
etcd
etcd
v0.4.7

搜索帮助

0d507c66 1850385 C8b1a773 1850385