Skip to content

Commit 20ae4a9

Browse files
buffered channel pattern.
1 parent 710b8b7 commit 20ae4a9

2 files changed

Lines changed: 230 additions & 0 deletions

File tree

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// This sample program demostrates how to use the pool package
2+
// to share a simulated set of database connections.
3+
package main
4+
5+
import (
6+
"fmt"
7+
"math/rand"
8+
"sync"
9+
"sync/atomic"
10+
"time"
11+
12+
"github.com/goinaction/code/chapter6/patterns/pool"
13+
)
14+
15+
const (
16+
// maxGoroutines is the number of routines to use.
17+
maxGoroutines = 25
18+
19+
// pooledResources is the number of resources to pool.
20+
pooledResources = 2
21+
)
22+
23+
var (
24+
// connectionID maintains a counter.
25+
connectionID int32
26+
27+
// mutex provides safe increments of ids
28+
mutex sync.Mutex
29+
30+
// wg is used to wait for the program to finish.
31+
wg sync.WaitGroup
32+
)
33+
34+
// dbConnection simulates a resource to share.
35+
type dbConnection struct {
36+
ID int32
37+
}
38+
39+
// Close implements the interface for the pool package.
40+
// Close performs any resource release management.
41+
func (dbConn *dbConnection) Close() {
42+
fmt.Println("Close: Connection", dbConn.ID)
43+
return
44+
}
45+
46+
// createConnection is a factory method called by the pool
47+
// framework when new connections are needed.
48+
func createConnection() (pool.Resource, error) {
49+
var id int32
50+
mutex.Lock()
51+
{
52+
id = atomic.AddInt32(&connectionID, 1)
53+
}
54+
mutex.Unlock()
55+
56+
fmt.Println("Create: New Connection", id)
57+
return &dbConnection{id}, nil
58+
}
59+
60+
// main is the entry point for all Go programs.
61+
func main() {
62+
// Add a count for each goroutine.
63+
wg.Add(maxGoroutines)
64+
65+
// Create the buffered channel to hold
66+
// and manage the connections.
67+
p := pool.New(createConnection, pooledResources)
68+
69+
// Perform queries using a connection from the pool.
70+
for query := 0; query < maxGoroutines; query++ {
71+
go performQueries(query, p)
72+
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
73+
}
74+
75+
// Wait for the goroutines to finish.
76+
wg.Wait()
77+
78+
// Close the pool.
79+
fmt.Println("*****> Shutdown Program.")
80+
p.Close()
81+
}
82+
83+
// performQueries tests the resource pool of connections.
84+
func performQueries(query int, p *pool.Pool) {
85+
// Schedule the call to Done to tell main we are done.
86+
defer wg.Done()
87+
88+
// Acquire a connection from the pool.
89+
conn, err := p.Acquire()
90+
if err != nil {
91+
fmt.Println(err)
92+
return
93+
}
94+
95+
// Release the connection back to the pool.
96+
defer p.Release(conn)
97+
98+
// Wait to simulate a query response.
99+
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
100+
fmt.Printf("Query: QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID)
101+
}

‎chapter6/patterns/pool/pool.go‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Package pool manages a user defined set of resources.
2+
// Based on the work by Fatih Arlan with his pool package.
3+
// https://github.com/fatih/pool/tree/v1.0.0
4+
package pool
5+
6+
import (
7+
"errors"
8+
"fmt"
9+
"sync"
10+
)
11+
12+
type (
13+
// Resource must be implemented by types to use the pool.
14+
Resource interface {
15+
Close()
16+
}
17+
18+
// Factory is a user supplied function that creates resources.
19+
Factory func() (Resource, error)
20+
)
21+
22+
type (
23+
// resources is a named type for the channel of resources.
24+
queue chan Resource
25+
26+
// Pool contains a queue of resources and methods that provide
27+
// support to share resources between goroutines.
28+
Pool struct {
29+
mutex sync.Mutex
30+
resources queue
31+
factory Factory
32+
}
33+
)
34+
35+
// New creates a pool for managing resources.
36+
func New(factory Factory, capacity int) *Pool {
37+
return &Pool{
38+
factory: factory,
39+
resources: make(queue, capacity),
40+
}
41+
}
42+
43+
// getQueue returns a safe copy of the resource queue.
44+
func (p *Pool) getQueue() queue {
45+
var resources queue
46+
p.mutex.Lock()
47+
{
48+
resources = p.resources
49+
}
50+
p.mutex.Unlock()
51+
52+
return resources
53+
}
54+
55+
// Acquire retrieves a resource from the pool.
56+
func (p *Pool) Acquire() (Resource, error) {
57+
// Get a safe copy of the resource queue and check
58+
// if the queue has been closed.
59+
resources := p.getQueue()
60+
if resources == nil {
61+
return nil, errors.New("Pool has been closed.")
62+
}
63+
64+
// The queue is still open so acquire a resource.
65+
66+
select {
67+
case resource := <-resources:
68+
fmt.Println("Acquire:", "Shared Resource")
69+
if resource == nil {
70+
return nil, errors.New("Pool has been closed.")
71+
}
72+
return resource, nil
73+
74+
default:
75+
fmt.Println("Acquire:", "New Resource")
76+
return p.factory()
77+
}
78+
}
79+
80+
// Release places the resource back into the queue or closes
81+
// the resource for good.
82+
func (p *Pool) Release(resource Resource) {
83+
p.mutex.Lock()
84+
defer p.mutex.Unlock()
85+
86+
// If the queue is closed, close the resource before returning.
87+
if p.resources == nil {
88+
resource.Close()
89+
return
90+
}
91+
92+
// The queue is still open so release the resource.
93+
94+
select {
95+
// Attempt to place the resource back into the queue first.
96+
// If the queue is full, this will block and the default case
97+
// will be executed.
98+
case p.resources <- resource:
99+
fmt.Println("Release:", "In Queue")
100+
101+
// The queue is full so just close this resource.
102+
default:
103+
fmt.Println("Release:", "Closing")
104+
resource.Close()
105+
}
106+
}
107+
108+
// Close will shutdown the pool and close all existing resources.
109+
func (p *Pool) Close() {
110+
// Get a safe copy of the queue and set the queue to nil.
111+
var resources queue
112+
p.mutex.Lock()
113+
{
114+
resources = p.resources
115+
p.resources = nil
116+
}
117+
p.mutex.Unlock()
118+
119+
// Is the queue already closed.
120+
if resources == nil {
121+
return
122+
}
123+
124+
// Close the queue and close all existing resources.
125+
close(resources)
126+
for resource := range resources {
127+
resource.Close()
128+
}
129+
}

0 commit comments

Comments
 (0)