Skip to content

Commit 4afe481

Browse files
authored
Merge pull request #31 from mahboubii/patch-1
Fix: race in memory provider
2 parents 9efc33b + 2b4ebe7 commit 4afe481

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

providers/memory/memory.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,21 @@ package memory
33
import (
44
"context"
55
"fmt"
6+
"sync"
67

78
"github.com/lileio/pubsub/v2"
89
)
910

1011
type MemoryProvider struct {
12+
mutex sync.RWMutex
1113
Msgs map[string][]*pubsub.Msg
1214
ErrorHandler func(err error)
1315
}
1416

1517
func (mp *MemoryProvider) Publish(ctx context.Context, topic string, m *pubsub.Msg) error {
18+
mp.mutex.Lock()
19+
defer mp.mutex.Unlock()
20+
1621
if mp.Msgs == nil {
1722
mp.Msgs = make(map[string][]*pubsub.Msg, 0)
1823
}
@@ -23,6 +28,9 @@ func (mp *MemoryProvider) Publish(ctx context.Context, topic string, m *pubsub.M
2328
}
2429

2530
func (mp *MemoryProvider) Subscribe(opts pubsub.HandlerOptions, h pubsub.MsgHandler) {
31+
mp.mutex.RLock()
32+
defer mp.mutex.RUnlock()
33+
2634
for _, v := range mp.Msgs[opts.Topic] {
2735
err := h(context.Background(), *v)
2836

0 commit comments

Comments
 (0)