Last active
April 20, 2016 18:14
-
-
Save bttmly/0fd7c2537694ded12024c1a1fc484383 to your computer and use it in GitHub Desktop.
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
package turbofan | |
import "reflect" | |
type Turbofan struct { | |
Blast func(bool) | |
} | |
// New just creates a new turbofan | |
func New(chans ...chan bool) *Turbofan { | |
t := &Turbofan{} | |
// http://stackoverflow.com/questions/19992334/how-to-listen-to-n-channels-dynamic-select-statement | |
cases := make([]reflect.SelectCase, len(chans)) | |
for i, ch := range chans { | |
cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)} | |
} | |
go func() { | |
for { | |
chosen, value, _ := reflect.Select(cases) | |
for j, ch := range chans { | |
if j != chosen { | |
ch <- value.Bool() | |
} | |
} | |
} | |
}() | |
t.Blast = func(b bool) { | |
for _, ch := range chans { | |
ch <- b | |
} | |
} | |
return t | |
} |
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
package turbofan_test | |
import ( | |
"log" | |
"github.com/nickb1080/turbofan" | |
. "github.com/onsi/ginkgo" | |
. "github.com/onsi/gomega" | |
) | |
var _ = Describe("Turbofan", func() { | |
var a, b, c chan bool | |
BeforeSuite(func() { | |
log.SetOutput(GinkgoWriter) | |
}) | |
BeforeEach(func() { | |
a = make(chan bool) | |
b = make(chan bool) | |
c = make(chan bool) | |
}) | |
Context("Turbofan", func() { | |
It("Other channels receive when one sends", func(done Done) { | |
turbofan.New(a, b, c) | |
go func() { | |
fromB := <-b | |
Expect(fromB).To(BeTrue()) | |
fromC := <-c | |
Expect(fromC).To(BeTrue()) | |
Consistently(a).ShouldNot(Receive()) | |
close(done) | |
}() | |
a <- true | |
}, 0.5) | |
It("All channels receive on .Blast()", func(done Done) { | |
t := turbofan.New(a, b, c) | |
go func() { | |
fromA := <-a | |
Expect(fromA).To(BeTrue()) | |
fromB := <-b | |
Expect(fromB).To(BeTrue()) | |
fromC := <-c | |
Expect(fromC).To(BeTrue()) | |
close(done) | |
}() | |
t.Blast(true) | |
}, 0.5) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment