Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 342fa99

Browse files
20220419
1 parent a50293a commit 342fa99

File tree

2 files changed

+91
-1
lines changed

2 files changed

+91
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ ps:白天上班,晚上更新,尽量日更,比心
6767

6868
[第29章 所有任务完成](https://github.com/java-aodeng/golang-examples/blob/master/go-29/all_done_test.go)
6969

70-
第30章 对象池
70+
[第30章 对象池](https://github.com/java-aodeng/golang-examples/blob/master/go-30/obj_pool_test.go)
7171

7272
第31章 sync.pool对象缓存
7373

‎go-30/obj_pool_test.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package go_30
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"testing"
7+
"time"
8+
)
9+
10+
/*
11+
对象池
12+
13+
go语言对象池 可以利用Buffered Channels来实现
14+
15+
*/
16+
17+
//定义一个对象
18+
type ReusableObj struct {
19+
}
20+
21+
//用于缓冲可重用对象
22+
type ObjPool struct {
23+
bufChan chan *ReusableObj
24+
}
25+
26+
func NewObjPool(numOfObj int) *ObjPool {
27+
objPool := ObjPool{}
28+
//创建的Buffered Channels 指定容量numOfObj
29+
objPool.bufChan = make(chan *ReusableObj, numOfObj)
30+
for i := 0; i < numOfObj; i++ {
31+
objPool.bufChan <- &ReusableObj{}
32+
}
33+
return &objPool
34+
}
35+
36+
func (p *ObjPool) GetObj(timeout time.Duration) (*ReusableObj, error) {
37+
select {
38+
case ret := <-p.bufChan:
39+
return ret, nil
40+
case <-time.After(timeout): //超时控制
41+
return nil, errors.New("超时")
42+
}
43+
}
44+
45+
func (p *ObjPool) ReleaseObj(obj *ReusableObj) error {
46+
select {
47+
case p.bufChan <- obj:
48+
return nil
49+
default:
50+
return errors.New("overflow")
51+
52+
}
53+
}
54+
55+
func TestObjPool(t *testing.T) {
56+
pool := NewObjPool(10)
57+
for i := 0; i < 11; i++ {
58+
if v, err := pool.GetObj(time.Second * 1); err != nil {
59+
t.Error(err)
60+
} else {
61+
fmt.Printf("%T\n", v)
62+
if err := pool.ReleaseObj(v); err != nil {
63+
t.Error(err)
64+
}
65+
}
66+
}
67+
fmt.Println("Done")
68+
}
69+
70+
/*运行结果
71+
=== RUN TestObjPool
72+
*go_30.ReusableObj
73+
*go_30.ReusableObj
74+
*go_30.ReusableObj
75+
*go_30.ReusableObj
76+
*go_30.ReusableObj
77+
*go_30.ReusableObj
78+
*go_30.ReusableObj
79+
*go_30.ReusableObj
80+
*go_30.ReusableObj
81+
*go_30.ReusableObj
82+
*go_30.ReusableObj
83+
Done
84+
--- PASS: TestObjPool (0.00s)
85+
PASS
86+
87+
88+
Process finished with the exit code 0
89+
90+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /