Created
November 29, 2012 16:13
-
-
Save ciniglio/4170068 to your computer and use it in GitHub Desktop.
Internal Channels Pattern
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
func main() { | |
t := NewThing(0) | |
var r int | |
for i := 0; i < 10; i++ { | |
r = t.inc() | |
} | |
} |
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
type Thing struct { | |
state int | |
internal chan message | |
} | |
type message struct { | |
f func(int) int | |
ret chan int | |
} | |
func NewThing(i int) Thing{ | |
t := new(Thing) | |
t.state = i | |
t.internal = make(chan message) | |
go t.run() | |
return t | |
} | |
func (t Thing) run() { | |
for m := range t.internal { | |
t.i = m.f(t.i) | |
m.ret <- t.i | |
} | |
} | |
func (t Thing) Inc() int{ | |
m := new(message) | |
m.f = func(i int){ return i + 1 } | |
m.ret = make(chan int) | |
t.internal <- m | |
return <- m.ret | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment