-
Notifications
You must be signed in to change notification settings - Fork 0
/
poolUse.go
78 lines (63 loc) · 1.36 KB
/
poolUse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"io"
"log"
"math/rand"
"sync"
"sync/atomic"
"time"
"github.com/lutaoact/go-exercise/pool"
)
const (
halfGoroutines = 10
maxGoroutines = 20
pooledResources = 10
)
type dbConnection struct {
ID int32
}
func (dbConn *dbConnection) Close() error {
log.Println("Close: Connection", dbConn.ID)
return nil
}
var idCouter int32
func createConnection() (io.Closer, error) {
id := atomic.AddInt32(&idCouter, 1)
log.Println("Create: New Connection", id)
return &dbConnection{id}, nil
}
func main() {
var wg sync.WaitGroup
wg.Add(maxGoroutines)
p, err := pool.New(createConnection, pooledResources)
if err != nil {
log.Println(err)
}
for query := 0; query < halfGoroutines; query++ {
go func(q int) {
performQueries(q, p)
wg.Done()
}(query)
}
//延时一会,让之前的任务处理完,资源还到通道中
time.Sleep(time.Duration(200) * time.Millisecond)
for query := halfGoroutines; query < maxGoroutines; query++ {
go func(q int) {
performQueries(q, p)
wg.Done()
}(query)
}
wg.Wait()
log.Println("Shutdown Program.")
p.Close()
}
func performQueries(query int, p *pool.Pool) {
conn, err := p.Acquire()
if err != nil {
log.Println(err)
return
}
defer p.Release(conn)
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
log.Printf("QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID)
}