Last active
August 29, 2015 13:57
-
-
Save menghan/9906087 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| package mix | |
| func Mix(high <-chan interface{}, low <-chan interface{}) <-chan interface{} { | |
| c := make(chan interface{}) | |
| go func() { | |
| defer close(c) | |
| var vh, vl interface{} | |
| highOpen := true | |
| lowOpen := true | |
| var ok bool | |
| for highOpen || lowOpen { | |
| select { | |
| case vh, ok = <-high: | |
| if !ok { | |
| highOpen = false | |
| high = nil | |
| break | |
| } | |
| c <- vh | |
| continue | |
| case vl, ok = <-low: | |
| if !ok { | |
| lowOpen = false | |
| low = nil | |
| break | |
| } | |
| lowloop: | |
| for { | |
| select { | |
| case c <- vl: | |
| break lowloop | |
| case vh, ok = <-high: | |
| if !ok { | |
| highOpen = false | |
| high = nil | |
| c <- vl | |
| break lowloop | |
| } | |
| c <- vh | |
| continue | |
| } | |
| } | |
| } | |
| } | |
| }() | |
| return c | |
| } |
This file contains hidden or 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
| package mix | |
| import ( | |
| "testing" | |
| "time" | |
| ) | |
| func TestDoubleChan(t *testing.T) { | |
| c1 := make(chan interface{}) | |
| c2 := make(chan interface{}) | |
| doubleChan := Mix(c1, c2) | |
| go func() { | |
| time.Sleep(time.Millisecond * 50) | |
| for i := 0; i < 3; i++ { | |
| c1 <- "one" | |
| time.Sleep(time.Millisecond * 50) | |
| } | |
| }() | |
| go func() { | |
| for i := 0; i < 3; i++ { | |
| c2 <- "two" | |
| time.Sleep(time.Millisecond * 50) | |
| } | |
| }() | |
| expects := []string{"two", "one", "one", "one", "two", "two"} | |
| for _, expect := range expects { | |
| msg := <-doubleChan | |
| t.Log(msg) | |
| if msg != expect { | |
| t.Error("Expect:", expect) | |
| } | |
| time.Sleep(time.Millisecond * 200) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment