Skip to content

Instantly share code, notes, and snippets.

@joaoh82
Created June 22, 2019 20:51
Show Gist options
  • Save joaoh82/22a69a6f696cf21417e7a3e415df3102 to your computer and use it in GitHub Desktop.
Save joaoh82/22a69a6f696cf21417e7a3e415df3102 to your computer and use it in GitHub Desktop.
package main
import "fmt"
import "golang.org/x/net/context"
// A message processes parameter and returns the result on resChan.
// ctx is places in a struct, but this is ok to do.
type message struct {
resChan chan<- int
parameter string
ctx context.Context
}
func ProcessMessages(work <-chan message) {
for job := range work {
select {
// If the context is finished, don't bother processing the
// message.
case <-job.ctx.Done():
continue
default:
}
// Assume this takes a long time to calculate
hardToCalculate := len(job.parameter)
select {
case <-job.ctx.Done():
case job.resChan <- hardToCalculate:
}
}
}
func newRequest(ctx context.Context, input string, q chan<- message) {
r := make(chan int)
select {
// If the context finishes before we can send msg onto q,
// exit early
case <-ctx.Done():
fmt.Println("Context ended before q could see message")
return
case q <- message{
resChan: r,
parameter: input,
// We are placing a context in a struct. This is ok since it
// is only stored as a passed message and we want q to know
// when it can discard this message
ctx: ctx,
}:
}
select {
case out := <-r:
fmt.Printf("length of %s is %d\n", input, out)
// If the context finishes before we could get the result, exit early
case <-ctx.Done():
fmt.Println("Context ended before q could process message")
}
}
func main() {
q := make(chan message)
go ProcessMessages(q)
ctx := context.Background()
newRequest(ctx, "hello", q)
newRequest(ctx, "my name is Joao", q)
close(q)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment