Skip to content

Instantly share code, notes, and snippets.

@bcho
Created February 12, 2016 12:17
Show Gist options
  • Save bcho/86ccd1163afa416609e1 to your computer and use it in GitHub Desktop.
Save bcho/86ccd1163afa416609e1 to your computer and use it in GitHub Desktop.

Revisions

  1. bcho created this gist Feb 12, 2016.
    60 changes: 60 additions & 0 deletions event_server.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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)
    }