Skip to content

Commit 39cabdf

Browse files
Merge pull request goinaction#8 from gbbr/pool-c7
Changes to make the example more idiomatic.
2 parents fb299db + b4d580a commit 39cabdf

2 files changed

Lines changed: 79 additions & 77 deletions

File tree

‎chapter7/patterns/pool/main/main.go‎

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,13 @@ import (
1515
)
1616

1717
const (
18-
// maxGoroutines is the number of routines to use.
19-
maxGoroutines = 25
20-
21-
// pooledResources is the number of resources to pool.
22-
pooledResources = 2
18+
maxGoroutines = 25 // the number of routines to use.
19+
pooledResources = 2 // number of resources in the pool
2320
)
2421

2522
var (
26-
// connectionID maintains a counter.
27-
connectionID int32
28-
29-
// wg is used to wait for the program to finish.
30-
wg sync.WaitGroup
23+
connectionID int32 // counter
24+
wg sync.WaitGroup // waits for program to finish
3125
)
3226

3327
// dbConnection simulates a resource to share.
@@ -39,21 +33,19 @@ type dbConnection struct {
3933
// Close performs any resource release management.
4034
func (dbConn *dbConnection) Close() {
4135
fmt.Println("Close: Connection", dbConn.ID)
42-
return
4336
}
4437

4538
// createConnection is a factory method called by the pool
4639
// framework when new connections are needed.
4740
func createConnection() (pool.Resource, error) {
4841
id := atomic.AddInt32(&connectionID, 1)
49-
5042
fmt.Println("Create: New Connection", id)
43+
5144
return &dbConnection{id}, nil
5245
}
5346

5447
// main is the entry point for all Go programs.
5548
func main() {
56-
// Add a count for each goroutine.
5749
wg.Add(maxGoroutines)
5850

5951
// Create the buffered channel to hold
@@ -64,8 +56,13 @@ func main() {
6456
}
6557

6658
// Perform queries using a connection from the pool.
67-
for query := 0; query < maxGoroutines; query++ {
68-
go performQueries(query, p)
59+
for q := 0; q < maxGoroutines; q++ {
60+
// TODO: Explain about closures and why we are using params
61+
go func(query int, pool pool.Interface) {
62+
performQueries(query, pool)
63+
wg.Done()
64+
}(q, p)
65+
6966
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
7067
}
7168

@@ -78,10 +75,7 @@ func main() {
7875
}
7976

8077
// performQueries tests the resource pool of connections.
81-
func performQueries(query int, p *pool.Pool) {
82-
// Schedule the call to Done to tell main we are done.
83-
defer wg.Done()
84-
78+
func performQueries(query int, p pool.Interface) {
8579
// Acquire a connection from the pool.
8680
conn, err := p.Acquire()
8781
if err != nil {

‎chapter7/patterns/pool/pool.go‎

Lines changed: 66 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -12,102 +12,110 @@ import (
1212
"sync"
1313
)
1414

15-
type (
16-
// Resource must be implemented by types to use the pool.
17-
Resource interface {
18-
Close()
19-
}
15+
// Pool manages a set of resources that can be acquired, released and closed.
16+
// We name it Interface because when the package is imported it will be used
17+
// as pool.Interface, which is better semantics.
18+
type Interface interface {
19+
Acquire() (Resource, error)
20+
Release(Resource)
21+
Close()
22+
}
2023

21-
// Factory is a user supplied function that creates resources.
22-
Factory func() (Resource, error)
23-
)
24+
// An interface allows us to decouple the pool from its implementation, which is
25+
// a good practice for writing testable and maintainable software.
2426

25-
type (
26-
// resources is a named type for the channel of resources.
27-
queue chan Resource
28-
29-
// Pool contains a queue of resources and methods that provide
30-
// support to share resources between goroutines.
31-
Pool struct {
32-
mutex sync.Mutex
33-
resources queue
34-
factory Factory
35-
closed bool
36-
}
37-
)
27+
// Resource must be implemented by types to use the pool.
28+
type Resource interface {
29+
Close()
30+
}
31+
32+
// Pool manages a set of resources that can be shared safely by multiple goroutines
33+
type pool struct {
34+
sync.Mutex
35+
resources chan Resource
36+
factory func() (Resource, error)
37+
closed bool
38+
}
3839

39-
// New creates a pool for managing resources.
40-
func New(factory Factory, capacity int) (*Pool, error) {
41-
// Check the capacity is greater than zero else
42-
// we could create an unbuffered channel or panic.
43-
if capacity <= 0 {
44-
return nil, fmt.Errorf("Invalid Capacity Value: %d", capacity)
40+
// ErrInvalidCapacity is returned when there has been an attempt to create an
41+
// unbuffered pool.
42+
var ErrInvalidCapacity = errors.New("Capacity needs to be greater than zero.")
43+
44+
// New creates a pool from a set of factory functions. A pool provides capacity
45+
// number of resources that can be shared safely by multiple goroutines.
46+
func New(fn func() (Resource, error), capacity uint) (*pool, error) {
47+
if capacity == 0 {
48+
return nil, ErrInvalidCapacity
4549
}
4650

47-
return &Pool{
48-
factory: factory,
49-
resources: make(queue, capacity),
51+
return &pool{
52+
factory: fn,
53+
resources: make(chan Resource, capacity),
5054
}, nil
5155
}
5256

5357
// Acquire retrieves a resource from the pool.
54-
func (p *Pool) Acquire() (Resource, error) {
58+
func (p *pool) Acquire() (Resource, error) {
5559
select {
56-
case resource, ok := <-p.resources:
60+
// Check for a free resource
61+
case r, ok := <-p.resources:
5762
fmt.Println("Acquire:", "Shared Resource")
5863
if !ok {
5964
return nil, errors.New("Pool has been closed.")
6065
}
61-
return resource, nil
66+
return r, nil
6267

68+
// Or provide a new one
6369
default:
6470
fmt.Println("Acquire:", "New Resource")
6571
return p.factory()
6672
}
6773
}
6874

69-
// Release places the resource back into the queue or closes
70-
// the resource for good.
71-
func (p *Pool) Release(resource Resource) {
75+
// Release places a new resource onto the pool
76+
func (p *pool) Release(r Resource) {
7277
// Secure this operation with the Close operation.
73-
p.mutex.Lock()
74-
defer p.mutex.Unlock()
78+
p.Lock()
79+
defer p.Unlock()
7580

76-
// If the pool is closed, close the resource before returning.
81+
// If the pool is closed, discard the resource.
7782
if p.closed {
78-
resource.Close()
83+
r.Close()
7984
return
8085
}
8186

82-
// The queue is still open so release the resource.
83-
8487
select {
85-
// Attempt to place the resource back into the queue first. If the queue
86-
// is full, then the default case will be executed.
87-
case p.resources <- resource:
88+
// Attempt to place the new resource on the queue.
89+
case p.resources <- r:
8890
fmt.Println("Release:", "In Queue")
8991

90-
// The queue is full so just close this resource.
92+
// If the queue is already at capacity we close the resource.
9193
default:
9294
fmt.Println("Release:", "Closing")
93-
resource.Close()
95+
r.Close()
9496
}
9597
}
9698

9799
// Close will shutdown the pool and close all existing resources.
98-
func (p *Pool) Close() {
100+
func (p *pool) Close() {
99101
// Secure this operation with the Release operation.
100-
p.mutex.Lock()
101-
defer p.mutex.Unlock()
102+
p.Lock()
103+
defer p.Unlock()
104+
105+
if p.closed {
106+
return
107+
}
102108

103-
// If the pool is not closed, the close it down.
104-
if !p.closed {
105-
p.closed = true
109+
// TODO: Explain why flag needs to be off before calling CLose() on each
110+
// resource
106111

107-
// Close the queue and close all existing resources.
108-
close(p.resources)
109-
for resource := range p.resources {
110-
resource.Close()
111-
}
112+
// Toggle the flag
113+
p.closed = true
114+
// Close the channel
115+
close(p.resources)
116+
117+
// Close the resources
118+
for r := range p.resources {
119+
r.Close()
112120
}
113121
}

0 commit comments

Comments
 (0)