Skip to content

Instantly share code, notes, and snippets.

@Darfk
Created September 25, 2018 23:50
Show Gist options
  • Save Darfk/bcc1d1e7e9e64237aadeba3579913b42 to your computer and use it in GitHub Desktop.
Save Darfk/bcc1d1e7e9e64237aadeba3579913b42 to your computer and use it in GitHub Desktop.
channels that grow to avoid blocking on send
package main
import (
"sync"
)
func main() {
inChannel := make(chan int)
outChannel := make(chan int)
mutex := sync.Mutex{}
channelBuffer := []chan int{
make(chan int, 1),
}
go func() {
channelBufferIndex := 0
for upstream := range inChannel {
mutex.Lock()
select {
case channelBuffer[channelBufferIndex] <- upstream:
default:
channelBuffer = append(channelBuffer, make(chan int, cap(channelBuffer[channelBufferIndex])*2))
println("grow", cap(channelBuffer[channelBufferIndex])*2)
close(channelBuffer[channelBufferIndex])
channelBufferIndex++
channelBuffer[channelBufferIndex] <- upstream
}
mutex.Unlock()
}
close(channelBuffer[channelBufferIndex])
}()
go func() {
channelBufferIndex := 0
for {
for upstream := range channelBuffer[channelBufferIndex] {
outChannel <- upstream
}
mutex.Lock()
channelBufferIndex++
if channelBufferIndex >= len(channelBuffer) {
break
}
mutex.Unlock()
}
mutex.Unlock()
close(outChannel)
}()
go func() {
for i := 0; i < 1024; i++ {
inChannel <- i
}
close(inChannel)
}()
for upstream := range outChannel {
print(upstream, " ")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment