Created
February 12, 2016 12:17
-
-
Save bcho/86ccd1163afa416609e1 to your computer and use it in GitHub Desktop.
trick
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 main | |
import "fmt" | |
type ev struct { | |
target interface{} | |
returnValue interface{} | |
c chan error | |
} | |
func server(c chan *ev) { | |
for { | |
select { | |
case event := <-c: | |
switch event.target.(type) { | |
case string: | |
event.returnValue = "hello, world" | |
event.c <- nil | |
break | |
case int: | |
event.returnValue = 42 | |
event.c <- nil | |
break | |
default: | |
fmt.Println("unknown type") | |
return | |
} | |
} | |
} | |
} | |
func stringClient(c chan *ev) { | |
e := &ev{target: "foo", c: make(chan error)} | |
c <- e | |
<-e.c // make sure server have handled the event | |
fmt.Println(e.returnValue.(string)) | |
} | |
func intClient(c chan *ev) { | |
e := &ev{target: 1024, c: make(chan error)} | |
c <- e | |
<-e.c | |
fmt.Printf("%d\n", e.returnValue.(int)) | |
} | |
func main() { | |
c := make(chan *ev) | |
go server(c) | |
for i := 0; i < 64; i++ { | |
go stringClient(c) | |
} | |
for i := 0; i < 64; i++ { | |
go intClient(c) | |
} | |
stringClient(c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment