-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
54 lines (51 loc) · 1016 Bytes
/
buffer.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
package lagoon
import (
"log"
"time"
)
type Buffer struct {
// safe
buffer chan struct{}
timeout time.Duration
}
func CreateBuffer(
max int,
timeout time.Duration,
) *Buffer {
if max <= 0 {
log.Fatalf("./lagoon.CreateBuffer(): max < 1: %d", max)
return nil
}
if timeout <= 0 {
log.Fatalf("./lagoon.CreateBuffer(): timeout < 1: %d", timeout)
return nil
}
return &Buffer{
buffer: make(chan struct{}, max),
timeout: timeout,
}
}
func (self *Buffer) GetMax() int {
return cap(self.buffer)
}
func (self *Buffer) GetTimeout() time.Duration {
return self.timeout
}
func (self *Buffer) acquire() bool {
// acquire from the buffer
select {
// this will block when the buffer becomes full
case self.buffer <- struct{}{}:
// successfully acquired!
// BUFFER MUST BE RELEASED
return true
case <-time.After(self.timeout):
// failed to acquire
// buffer will not have to be released!!!
return false
}
}
func (self *Buffer) release() {
// release from the buffer
<-self.buffer
}