Skip to content

Instantly share code, notes, and snippets.

@exupero
Created July 19, 2012 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exupero/3140066 to your computer and use it in GitHub Desktop.
Save exupero/3140066 to your computer and use it in GitHub Desktop.
Passing channels over channels to create a connection pool
package main
import (
"fmt"
"math/rand"
"time"
)
type Request struct {}
func connect(trigger chan bool, ch chan (chan Request)) {
for {
conn := make(chan Request)
// ...get a connection and set it up to communicate on 'conn'...
ch <- conn
<-trigger // block until signalled
}
}
func main() {
var pool []chan Request
trigger := make(chan bool)
ch := make(chan (chan Request))
for i := 0; i < 3; i++ {
go connect(trigger, ch)
}
go func() {
for {
if rand.Float32() > 0.5 {
trigger <- true
}
time.Sleep(2 * time.Second)
}
}()
for conn := range ch {
pool = append(pool, conn)
fmt.Println("Created connection.")
fmt.Println(pool)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment