deferrwl.go 885 B

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