| 82 | } |
| 83 | |
| 84 | func (buf *SharedBuffer) mainLoop() { |
| 85 | for { |
| 86 | i, val, ok := reflect.Select(buf.cases) |
| 87 | |
| 88 | if i == 0 { |
| 89 | if !ok { |
| 90 | //Close was called on the SharedBuffer itself |
| 91 | return |
| 92 | } |
| 93 | |
| 94 | //NewChannel was called on the SharedBuffer |
| 95 | ch := val.Interface().(*sharedBufferChannel) |
| 96 | buf.chans = append(buf.chans, ch) |
| 97 | buf.cases = append(buf.cases, |
| 98 | reflect.SelectCase{Dir: reflect.SelectRecv}, |
| 99 | reflect.SelectCase{Dir: reflect.SelectSend}, |
| 100 | ) |
| 101 | if buf.size == Infinity || buf.count < int(buf.size) { |
| 102 | buf.cases[len(buf.cases)-2].Chan = reflect.ValueOf(ch.in) |
| 103 | } |
| 104 | } else if i%2 == 0 { |
| 105 | //Send |
| 106 | if buf.count == int(buf.size) { |
| 107 | //room in the buffer again, re-enable all recv cases |
| 108 | for j := range buf.chans { |
| 109 | if !buf.chans[j].closed { |
| 110 | buf.cases[(j*2)+1].Chan = reflect.ValueOf(buf.chans[j].in) |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | buf.count-- |
| 115 | ch := buf.chans[(i-1)/2] |
| 116 | if ch.buf.Length() > 0 { |
| 117 | buf.cases[i].Send = reflect.ValueOf(ch.buf.Peek()) |
| 118 | ch.buf.Remove() |
| 119 | } else { |
| 120 | //nothing left for this channel to send, disable sending |
| 121 | buf.cases[i].Chan = reflect.Value{} |
| 122 | buf.cases[i].Send = reflect.Value{} |
| 123 | if ch.closed { |
| 124 | // and it was closed, so close the output channel |
| 125 | //TODO: shrink slice |
| 126 | close(ch.out) |
| 127 | } |
| 128 | } |
| 129 | } else { |
| 130 | ch := buf.chans[i/2] |
| 131 | if ok { |
| 132 | //Receive |
| 133 | buf.count++ |
| 134 | if ch.buf.Length() == 0 && !buf.cases[i+1].Chan.IsValid() { |
| 135 | //this channel now has something to send |
| 136 | buf.cases[i+1].Chan = reflect.ValueOf(ch.out) |
| 137 | buf.cases[i+1].Send = val |
| 138 | } else { |
| 139 | ch.buf.Add(val.Interface()) |
| 140 | } |
| 141 | if buf.count == int(buf.size) { |