Created
January 12, 2012 01:27
-
-
Save kylelemons/1597888 to your computer and use it in GitHub Desktop.
Infinite channel buffer without "sync"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assume the following exist and are set to unbuffered channels: | |
// var ( | |
// next chan Type | |
// in chan Type | |
// ) | |
go func() { | |
defer close(next) | |
// pending events (this is the "infinite" part) | |
pending := []Type{} | |
recv: | |
for { | |
// Ensure that pending always has values so the select can | |
// multiplex between the receiver and sender properly | |
if len(pending) == 0 { | |
v, ok := <-in | |
if !ok { | |
// in is closed, flush values | |
break | |
} | |
pending = append(pending, v) | |
} | |
select { | |
// Queue incoming values | |
case v, ok := <-in: | |
if !ok { | |
// in is closed, flush values | |
break recv | |
} | |
pending = append(pending, v) | |
// Send values to the outer function | |
case next <- pending[0]: | |
pending = pending[1:] | |
} | |
} | |
// After in is closed, we may still have events to send | |
for _, v := range pending { | |
next <- v | |
} | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment