]> Sergey Matveev's repositories - btrtrc.git/blob - deferrwl.go
Drop support for go 1.20
[btrtrc.git] / deferrwl.go
1 package torrent
2
3 import "github.com/anacrolix/sync"
4
5 // Runs deferred actions on Unlock. Note that actions are assumed to be the results of changes that
6 // would only occur with a write lock at present. The race detector should catch instances of defers
7 // without the write lock being held.
8 type lockWithDeferreds struct {
9         internal      sync.RWMutex
10         unlockActions []func()
11 }
12
13 func (me *lockWithDeferreds) Lock() {
14         me.internal.Lock()
15 }
16
17 func (me *lockWithDeferreds) Unlock() {
18         unlockActions := me.unlockActions
19         for i := 0; i < len(unlockActions); i += 1 {
20                 unlockActions[i]()
21         }
22         me.unlockActions = unlockActions[:0]
23         me.internal.Unlock()
24 }
25
26 func (me *lockWithDeferreds) RLock() {
27         me.internal.RLock()
28 }
29
30 func (me *lockWithDeferreds) RUnlock() {
31         me.internal.RUnlock()
32 }
33
34 func (me *lockWithDeferreds) Defer(action func()) {
35         me.unlockActions = append(me.unlockActions, action)
36 }