Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You pretty much described the best way to do it but here is a small sample of code that does it.</p> <p>Go playground: <a href="https://play.golang.org/p/jwdtDXVHJk" rel="noreferrer">https://play.golang.org/p/jwdtDXVHJk</a></p> <pre><code>package main import ( "fmt" "time" ) func producer(iters int) &lt;-chan int { c := make(chan int) go func() { for i := 0; i &lt; iters; i++ { c &lt;- i time.Sleep(1 * time.Second) } close(c) }() return c } func consumer(cin &lt;-chan int) { for i := range cin { fmt.Println(i) } } func fanOut(ch &lt;-chan int, size, lag int) []chan int { cs := make([]chan int, size) for i, _ := range cs { // The size of the channels buffer controls how far behind the recievers // of the fanOut channels can lag the other channels. cs[i] = make(chan int, lag) } go func() { for i := range ch { for _, c := range cs { c &lt;- i } } for _, c := range cs { // close all our fanOut channels when the input channel is exhausted. close(c) } }() return cs } func fanOutUnbuffered(ch &lt;-chan int, size int) []chan int { cs := make([]chan int, size) for i, _ := range cs { // The size of the channels buffer controls how far behind the recievers // of the fanOut channels can lag the other channels. cs[i] = make(chan int) } go func() { for i := range ch { for _, c := range cs { c &lt;- i } } for _, c := range cs { // close all our fanOut channels when the input channel is exhausted. close(c) } }() return cs } func main() { c := producer(10) chans := fanOutUnbuffered(c, 3) go consumer(chans[0]) go consumer(chans[1]) consumer(chans[2]) } </code></pre> <p>The important part to note is how we close the output channels once the input channel has been exhausted. Also if one of the output channels blocks on the send it will hold up the send on the other output channels. We control the amount of lag by setting the buffer size of the channels.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload