2
0

Make simpler example

This commit is contained in:
Jack Christensen
2018-12-26 18:51:04 -06:00
parent 5cb5ce10c3
commit 3d17e25ee5
+42 -52
View File
@@ -591,82 +591,72 @@ func TestStress(t *testing.T) {
pool.Close()
}
func exampleDummyServer(laddr string, acceptCount int, recvCountChan chan int) {
func startAcceptOnceDummyServer(laddr string) {
ln, err := net.Listen("tcp", laddr)
if err != nil {
log.Fatalln("Listen:", err)
}
for i := 0; i < acceptCount; i++ {
// Listen one time
go func() {
conn, err := ln.Accept()
if err != nil {
log.Fatalln("Accept:", err)
}
go func() {
recvCount := 0
for {
buf := make([]byte, 1)
_, err := conn.Read(buf)
if err != nil {
recvCountChan <- recvCount
return
}
recvCount += 1
for {
buf := make([]byte, 1)
_, err := conn.Read(buf)
if err != nil {
return
}
}()
}
}
}()
}
func Example_Pool() {
func ExamplePool() {
// Dummy server
maxPoolSize := 4
serverRecvCountChan := make(chan int)
laddr := "127.0.0.1:8080"
startAcceptOnceDummyServer(laddr)
// exampleDummyServer only listens maxPoolSize times so if the pool tried to
// connect more than that the pool would receive an error.
go exampleDummyServer(laddr, maxPoolSize, serverRecvCountChan)
// Pool creation
constructor := func(context.Context) (interface{}, error) {
return net.Dial("tcp", laddr)
}
destructor := func(value interface{}) {
value.(net.Conn).Close()
}
maxPoolSize := 10
// Pool usage
pool := puddle.NewPool(
func(context.Context) (interface{}, error) { return net.Dial("tcp", laddr) },
func(value interface{}) { value.(net.Conn).Close() },
maxPoolSize,
)
pool := puddle.NewPool(constructor, destructor, maxPoolSize)
clientCount := 32
opPerClientCount := 100
wg := &sync.WaitGroup{}
// Use pool multiple times
for i := 0; i < 10; i++ {
// Acquire resource
res, err := pool.Acquire(context.Background())
if err != nil {
log.Fatalln("Acquire", err)
}
for i := 0; i < clientCount; i++ {
wg.Add(1)
go func() {
for i := 0; i < opPerClientCount; i++ {
res, err := pool.Acquire(context.Background())
if err != nil {
log.Fatalln("Acquire", err)
}
_, err = res.Value().(net.Conn).Write([]byte{1})
if err != nil {
log.Fatalln("Write", err)
}
res.Release()
}
wg.Done()
}()
// Type-assert value and use
_, err = res.Value().(net.Conn).Write([]byte{1})
if err != nil {
log.Fatalln("Write", err)
}
// Release when done.
res.Release()
}
wg.Wait()
stats := pool.Stat()
pool.Close()
totalRecv := <-serverRecvCountChan
totalRecv += <-serverRecvCountChan
totalRecv += <-serverRecvCountChan
totalRecv += <-serverRecvCountChan
fmt.Println("Ops:", totalRecv)
fmt.Println("Connections:", stats.TotalResources())
fmt.Println("Acquires:", stats.AcquireCount())
// Output:
// Ops: 3200
// Connections: 1
// Acquires: 10
}
func BenchmarkPoolAcquireAndRelease(b *testing.B) {