This repository has been archived by the owner on Feb 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfile_reader_pool.go
84 lines (66 loc) · 1.7 KB
/
file_reader_pool.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
package butteredscones
import (
"sync"
)
type FileReaderPool struct {
available map[string]*FileReader
locked map[string]*FileReader
lock sync.RWMutex
}
func NewFileReaderPool() *FileReaderPool {
return &FileReaderPool{
available: make(map[string]*FileReader),
locked: make(map[string]*FileReader),
}
}
func (p *FileReaderPool) Counts() (available int, locked int) {
p.lock.RLock()
defer p.lock.RUnlock()
return len(p.available), len(p.locked)
}
// TODO: Figure out how to make this block, rather than return nil
func (p *FileReaderPool) LockNext() *FileReader {
p.lock.Lock()
defer p.lock.Unlock()
for filePath, reader := range p.available {
delete(p.available, filePath)
p.locked[filePath] = reader
return reader
}
// Nothing available to lock
return nil
}
func (p *FileReaderPool) Unlock(reader *FileReader) {
p.lock.Lock()
defer p.lock.Unlock()
filePath := reader.FilePath()
delete(p.locked, filePath)
p.available[filePath] = reader
}
func (p *FileReaderPool) UnlockAll(readers []*FileReader) {
p.lock.Lock()
defer p.lock.Unlock()
for _, reader := range readers {
filePath := reader.FilePath()
delete(p.locked, filePath)
p.available[filePath] = reader
}
}
func (p *FileReaderPool) IsPathInPool(filePath string) bool {
p.lock.RLock()
defer p.lock.RUnlock()
return (p.available[filePath] != nil || p.locked[filePath] != nil)
}
func (p *FileReaderPool) Add(reader *FileReader) {
p.lock.Lock()
defer p.lock.Unlock()
filePath := reader.FilePath()
p.available[filePath] = reader
}
func (p *FileReaderPool) Remove(reader *FileReader) {
p.lock.Lock()
defer p.lock.Unlock()
filePath := reader.FilePath()
delete(p.available, filePath)
delete(p.locked, filePath)
}