File: outbound.go

package info (click to toggle)
golang-github-inconshreveable-muxado 0.0~git20140312.0.f693c7e-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 256 kB
  • ctags: 374
  • sloc: makefile: 2
file content (59 lines) | stat: -rw-r--r-- 744 bytes parent folder | download | duplicates (3)
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
package buffer

import (
	"sync"
)

type Outbound struct {
	val int
	err error
	*sync.Cond
}

func NewOutbound(size int) *Outbound {
	return &Outbound{val: size, Cond: sync.NewCond(new(sync.Mutex))}
}

func (b *Outbound) Increment(inc int) {
	b.L.Lock()
	b.val += inc
	b.Broadcast()
	b.L.Unlock()
}

func (b *Outbound) SetError(err error) {
	b.L.Lock()
	b.err = err
	b.Broadcast()
	b.L.Unlock()
}

func (b *Outbound) Decrement(dec int) (ret int, err error) {
	if dec == 0 {
		return
	}

	b.L.Lock()
	for {
		if b.err != nil {
			err = b.err
			break
		}

		if b.val > 0 {
			if dec > b.val {
				ret = b.val
				b.val = 0
				break
			} else {
				b.val -= dec
				ret = dec
				break
			}
		} else {
			b.Wait()
		}
	}
	b.L.Unlock()
	return
}