File: singleflight.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (49 lines) | stat: -rw-r--r-- 741 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package missinggo

import "sync"

type ongoing struct {
	do    sync.Mutex
	users int
}

type SingleFlight struct {
	mu      sync.Mutex
	ongoing map[string]*ongoing
}

type Operation struct {
	sf *SingleFlight
	id string
}

func (op Operation) Unlock() {
	op.sf.Unlock(op.id)
}

func (me *SingleFlight) Lock(id string) Operation {
	me.mu.Lock()
	on, ok := me.ongoing[id]
	if !ok {
		on = new(ongoing)
		if me.ongoing == nil {
			me.ongoing = make(map[string]*ongoing)
		}
		me.ongoing[id] = on
	}
	on.users++
	me.mu.Unlock()
	on.do.Lock()
	return Operation{me, id}
}

func (me *SingleFlight) Unlock(id string) {
	me.mu.Lock()
	on := me.ongoing[id]
	on.do.Unlock()
	on.users--
	if on.users == 0 {
		delete(me.ongoing, id)
	}
	me.mu.Unlock()
}