-
Notifications
You must be signed in to change notification settings - Fork 2
/
SendLimitedReaderProxy.dot.go
76 lines (68 loc) · 2.07 KB
/
SendLimitedReaderProxy.dot.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
// Copyright 2017 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io
// This file was generated with dotgo
// DO NOT EDIT - Improve the pattern!
// Note: SendProxyLimitedReader imports "container/ring" for the expanding buffer.
import (
"container/ring"
"io"
)
// LimitedReaderCAP is the capacity of the buffered proxy channel
const LimitedReaderCAP = 10
// LimitedReaderQUE is the allocated size of the circular queue
const LimitedReaderQUE = 16
// SendProxyLimitedReader returns a channel to serve as a sending proxy to 'out'.
// Uses a goroutine to receive values from 'out' and store them
// in an expanding buffer, so that sending to 'out' never blocks.
//
// Note: the expanding buffer is implemented via "container/ring"
func SendProxyLimitedReader(out chan<- *io.LimitedReader) chan<- *io.LimitedReader {
proxy := make(chan *io.LimitedReader, LimitedReaderCAP)
go func() {
n := LimitedReaderQUE // the allocated size of the circular queue
first := ring.New(n)
last := first
var c chan<- *io.LimitedReader
var e *io.LimitedReader
for {
c = out
if first == last {
// buffer empty: disable output
c = nil
} else {
e = first.Value.(*io.LimitedReader)
}
select {
case e = <-proxy:
last.Value = e
if last.Next() == first {
// buffer full: expand it
last.Link(ring.New(n))
n *= 2
}
last = last.Next()
case c <- e:
first = first.Next()
}
}
}()
return proxy
}
/* usage as found in $GOROOT/test/chan/sieve2.go
func Sieve() {
// ...
primes := make(chan int, 10)
primes <- 3
// ...
go func() {
// In order to generate the nth prime we only need multiples of primes ≤ sqrt(nth prime).
// Thus, the merging goroutine will receive from 'primes' much slower than this goroutine will send to it,
// making the buffer accumulate and block this goroutine from sending, causing a deadlock.
// The solution is to use a proxy goroutine to do automatic buffering.
primes := sendproxy(primes)
// ...
}()
}
*/