Skip to content

Commit 5fc9600

Browse files
committed
fix: data race for callback
Signed-off-by: closetool <c299999999@qq.com>
1 parent 0c4b40b commit 5fc9600

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

watcher.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"log"
2020
"runtime"
2121
"strconv"
22+
"sync"
2223
"time"
2324

2425
"github.com/casbin/casbin/v2/persist"
@@ -27,6 +28,8 @@ import (
2728
)
2829

2930
type Watcher struct {
31+
// lock for callback
32+
lock sync.RWMutex
3033
endpoints []string
3134
client *client.Client
3235
running bool
@@ -89,6 +92,8 @@ func (w *Watcher) createClient() error {
8992
// when the policy in DB has been changed by other instances.
9093
// A classic callback is Enforcer.LoadPolicy().
9194
func (w *Watcher) SetUpdateCallback(callback func(string)) error {
95+
w.lock.Lock()
96+
defer w.lock.Unlock()
9297
w.callback = callback
9398
return nil
9499
}
@@ -127,9 +132,11 @@ func (w *Watcher) startWatch() error {
127132
for res := range watcher {
128133
t := res.Events[0]
129134
if t.IsCreate() || t.IsModify() {
135+
w.lock.RLock()
130136
if w.callback != nil {
131137
w.callback(string(t.Kv.Value))
132138
}
139+
w.lock.RUnlock()
133140
}
134141

135142
}

0 commit comments

Comments
 (0)