-
Notifications
You must be signed in to change notification settings - Fork 51
/
locked_writer.go
87 lines (65 loc) · 1.18 KB
/
locked_writer.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"io"
"sync"
)
type sharedLock struct {
sync.Locker
held *struct {
sync.Locker
clients int
locked bool
}
}
func newSharedLock(lock sync.Locker, clients int) *sharedLock {
return &sharedLock{
Locker: lock,
held: &struct {
sync.Locker
clients int
locked bool
}{
Locker: &sync.Mutex{},
clients: clients,
locked: false,
},
}
}
func (mutex *sharedLock) Lock() {
mutex.held.Lock()
defer mutex.held.Unlock()
if !mutex.held.locked {
mutex.Locker.Lock()
mutex.held.locked = true
}
}
func (mutex *sharedLock) Unlock() {
mutex.held.Lock()
defer mutex.held.Unlock()
mutex.held.clients--
if mutex.held.clients == 0 && mutex.held.locked {
mutex.held.locked = false
mutex.Locker.Unlock()
}
}
type lockedWriter struct {
writer io.WriteCloser
lock sync.Locker
}
func newLockedWriter(
writer io.WriteCloser,
lock sync.Locker,
) *lockedWriter {
return &lockedWriter{
writer: writer,
lock: lock,
}
}
func (writer *lockedWriter) Write(data []byte) (int, error) {
writer.lock.Lock()
return writer.writer.Write(data)
}
func (writer *lockedWriter) Close() error {
writer.lock.Unlock()
return writer.writer.Close()
}