| 1 |
package buffer |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
) |
| 6 |
|
| 7 |
type Outbound struct { |
| 8 |
val int |
| 9 |
err error |
| 10 |
*sync.Cond |
| 11 |
} |
| 12 |
|
| 13 |
func NewOutbound(size int) *Outbound { |
| 14 |
return &Outbound{val: size, Cond: sync.NewCond(new(sync.Mutex))} |
| 15 |
} |
| 16 |
|
| 17 |
func (b *Outbound) Increment(inc int) { |
| 18 |
b.L.Lock() |
| 19 |
b.val += inc |
| 20 |
b.Broadcast() |
| 21 |
b.L.Unlock() |
| 22 |
} |
| 23 |
|
| 24 |
func (b *Outbound) SetError(err error) { |
| 25 |
b.L.Lock() |
| 26 |
b.err = err |
| 27 |
b.Broadcast() |
| 28 |
b.L.Unlock() |
| 29 |
} |
| 30 |
|
| 31 |
func (b *Outbound) Decrement(dec int) (ret int, err error) { |
| 32 |
if dec == 0 { |
| 33 |
return |
| 34 |
} |
| 35 |
|
| 36 |
b.L.Lock() |
| 37 |
for { |
| 38 |
if b.err != nil { |
| 39 |
err = b.err |
| 40 |
break |
| 41 |
} |
| 42 |
|
| 43 |
if b.val > 0 { |
| 44 |
if dec > b.val { |
| 45 |
ret = b.val |
| 46 |
b.val = 0 |
| 47 |
break |
| 48 |
} else { |
| 49 |
b.val -= dec |
| 50 |
ret = dec |
| 51 |
break |
| 52 |
} |
| 53 |
} else { |
| 54 |
b.Wait() |
| 55 |
} |
| 56 |
} |
| 57 |
b.L.Unlock() |
| 58 |
return |
| 59 |
} |