Created
July 19, 2012 00:59
-
-
Save exupero/3140066 to your computer and use it in GitHub Desktop.
Passing channels over channels to create a connection pool
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
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