Skip to content

Commit

Permalink
Fix concurrency issues events #88
Browse files Browse the repository at this point in the history
  • Loading branch information
joyrex2001 committed Jul 23, 2024
1 parent e429a72 commit d0449a5
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions internal/events/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type Events interface {

// instance is the internal representation of the Events object.
type instance struct {
mu sync.Mutex
observers map[string]chan Message
}

Expand Down Expand Up @@ -46,6 +47,8 @@ func (e *instance) Publish(id, typ, action string) {
// Subscribe will subscribe to the events and will return a channel and an
// unique identifier than can be used to unsubscribe when done.
func (e *instance) Subscribe() (<-chan Message, string) {
e.mu.Lock()
defer e.mu.Unlock()
out := make(chan Message, 1)
id := stringid.GenerateRandomID()
e.observers[id] = out
Expand All @@ -55,6 +58,8 @@ func (e *instance) Subscribe() (<-chan Message, string) {

// Unsubscribe will unsubscribe given subscriber id from the events.
func (e *instance) Unsubscribe(id string) {
e.mu.Lock()
defer e.mu.Unlock()
klog.V(5).Infof("unsubscribing %s from events", id)
delete(e.observers, id)
}
Expand Down

0 comments on commit d0449a5

Please sign in to comment.