Skip to content

Commit 4d25363

Browse files
committed
test: add some basic testable examples
1 parent 60bd4c4 commit 4d25363

12 files changed

+546
-694
lines changed

Diff for: README.md

+14-189
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Library `ants` implements a goroutine pool with fixed capacity, managing and rec
2525
- Purging overdue goroutines periodically
2626
- Abundant APIs: submitting tasks, getting the number of running goroutines, tuning the capacity of the pool dynamically, releasing the pool, rebooting the pool, etc.
2727
- Handle panic gracefully to prevent programs from crash
28-
- Efficient in memory usage and it may even achieve ***higher performance*** than unlimited goroutines in Golang
28+
- Efficient in memory usage and it may even achieve ***higher performance*** than unlimited goroutines in Go
2929
- Nonblocking mechanism
3030
- Preallocated memory (ring buffer, optional)
3131

@@ -62,205 +62,30 @@ go get -u github.com/panjf2000/ants/v2
6262
```
6363

6464
## 🛠 How to use
65-
Just imagine that your program starts a massive number of goroutines, resulting in a huge consumption of memory. To mitigate that kind of situation, all you need to do is to import `ants` package and submit all your tasks to a default pool with fixed capacity, activated when package `ants` is imported:
65+
Check out [the examples](https://pkg.go.dev/github.com/panjf2000/ants/v2#pkg-examples) for basic usage.
6666

67-
``` go
68-
package main
69-
70-
import (
71-
"fmt"
72-
"sync"
73-
"sync/atomic"
74-
"time"
75-
76-
"github.com/panjf2000/ants/v2"
77-
)
78-
79-
var sum int32
80-
81-
func myFunc(i any) {
82-
n := i.(int32)
83-
atomic.AddInt32(&sum, n)
84-
fmt.Printf("run with %d\n", n)
85-
}
86-
87-
func demoFunc() {
88-
time.Sleep(10 * time.Millisecond)
89-
fmt.Println("Hello World!")
90-
}
91-
92-
func main() {
93-
defer ants.Release()
94-
95-
runTimes := 1000
96-
97-
// Use the common pool.
98-
var wg sync.WaitGroup
99-
syncCalculateSum := func() {
100-
demoFunc()
101-
wg.Done()
102-
}
103-
for i := 0; i < runTimes; i++ {
104-
wg.Add(1)
105-
_ = ants.Submit(syncCalculateSum)
106-
}
107-
wg.Wait()
108-
fmt.Printf("running goroutines: %d\n", ants.Running())
109-
fmt.Printf("finish all tasks.\n")
110-
111-
// Use the pool with a function,
112-
// set 10 to the capacity of goroutine pool and 1 second for expired duration.
113-
p, _ := ants.NewPoolWithFunc(10, func(i any) {
114-
myFunc(i)
115-
wg.Done()
116-
})
117-
defer p.Release()
118-
// Submit tasks one by one.
119-
for i := 0; i < runTimes; i++ {
120-
wg.Add(1)
121-
_ = p.Invoke(int32(i))
122-
}
123-
wg.Wait()
124-
fmt.Printf("running goroutines: %d\n", p.Running())
125-
fmt.Printf("finish all tasks, result is %d\n", sum)
126-
if sum != 499500 {
127-
panic("the final result is wrong!!!")
128-
}
129-
130-
// Use the MultiPool and set the capacity of the 10 goroutine pools to unlimited.
131-
// If you use -1 as the pool size parameter, the size will be unlimited.
132-
// There are two load-balancing algorithms for pools: ants.RoundRobin and ants.LeastTasks.
133-
mp, _ := ants.NewMultiPool(10, -1, ants.RoundRobin)
134-
defer mp.ReleaseTimeout(5 * time.Second)
135-
for i := 0; i < runTimes; i++ {
136-
wg.Add(1)
137-
_ = mp.Submit(syncCalculateSum)
138-
}
139-
wg.Wait()
140-
fmt.Printf("running goroutines: %d\n", mp.Running())
141-
fmt.Printf("finish all tasks.\n")
142-
143-
// Use the MultiPoolFunc and set the capacity of 10 goroutine pools to (runTimes/10).
144-
mpf, _ := ants.NewMultiPoolWithFunc(10, runTimes/10, func(i any) {
145-
myFunc(i)
146-
wg.Done()
147-
}, ants.LeastTasks)
148-
defer mpf.ReleaseTimeout(5 * time.Second)
149-
for i := 0; i < runTimes; i++ {
150-
wg.Add(1)
151-
_ = mpf.Invoke(int32(i))
152-
}
153-
wg.Wait()
154-
fmt.Printf("running goroutines: %d\n", mpf.Running())
155-
fmt.Printf("finish all tasks, result is %d\n", sum)
156-
if sum != 499500*2 {
157-
panic("the final result is wrong!!!")
158-
}
159-
}
160-
```
161-
162-
### Functional options for ants pool
67+
### Functional options for pool
16368

164-
```go
165-
// Option represents the optional function.
166-
type Option func(opts *Options)
167-
168-
// Options contains all options which will be applied when instantiating a ants pool.
169-
type Options struct {
170-
// ExpiryDuration is a period for the scavenger goroutine to clean up those expired workers,
171-
// the scavenger scans all workers every `ExpiryDuration` and clean up those workers that haven't been
172-
// used for more than `ExpiryDuration`.
173-
ExpiryDuration time.Duration
174-
175-
// PreAlloc indicates whether to make memory pre-allocation when initializing Pool.
176-
PreAlloc bool
177-
178-
// Max number of goroutine blocking on pool.Submit.
179-
// 0 (default value) means no such limit.
180-
MaxBlockingTasks int
181-
182-
// When Nonblocking is true, Pool.Submit will never be blocked.
183-
// ErrPoolOverload will be returned when Pool.Submit cannot be done at once.
184-
// When Nonblocking is true, MaxBlockingTasks is inoperative.
185-
Nonblocking bool
186-
187-
// PanicHandler is used to handle panics from each worker goroutine.
188-
// if nil, panics will be thrown out again from worker goroutines.
189-
PanicHandler func(any)
190-
191-
// Logger is the customized logger for logging info, if it is not set,
192-
// default standard logger from log package is used.
193-
Logger Logger
194-
}
195-
196-
// WithOptions accepts the whole options config.
197-
func WithOptions(options Options) Option {
198-
return func(opts *Options) {
199-
*opts = options
200-
}
201-
}
202-
203-
// WithExpiryDuration sets up the interval time of cleaning up goroutines.
204-
func WithExpiryDuration(expiryDuration time.Duration) Option {
205-
return func(opts *Options) {
206-
opts.ExpiryDuration = expiryDuration
207-
}
208-
}
209-
210-
// WithPreAlloc indicates whether it should malloc for workers.
211-
func WithPreAlloc(preAlloc bool) Option {
212-
return func(opts *Options) {
213-
opts.PreAlloc = preAlloc
214-
}
215-
}
216-
217-
// WithMaxBlockingTasks sets up the maximum number of goroutines that are blocked when it reaches the capacity of pool.
218-
func WithMaxBlockingTasks(maxBlockingTasks int) Option {
219-
return func(opts *Options) {
220-
opts.MaxBlockingTasks = maxBlockingTasks
221-
}
222-
}
223-
224-
// WithNonblocking indicates that pool will return nil when there is no available workers.
225-
func WithNonblocking(nonblocking bool) Option {
226-
return func(opts *Options) {
227-
opts.Nonblocking = nonblocking
228-
}
229-
}
230-
231-
// WithPanicHandler sets up panic handler.
232-
func WithPanicHandler(panicHandler func(any)) Option {
233-
return func(opts *Options) {
234-
opts.PanicHandler = panicHandler
235-
}
236-
}
237-
238-
// WithLogger sets up a customized logger.
239-
func WithLogger(logger Logger) Option {
240-
return func(opts *Options) {
241-
opts.Logger = logger
242-
}
243-
}
244-
```
69+
`ants.Options`contains all optional configurations of the ants pool, which allows you to customize the goroutine pool by invoking option functions to set up each configuration in `NewPool`/`NewPoolWithFunc`/`NewPoolWithFuncGeneric` method.
24570

246-
`ants.Options`contains all optional configurations of the ants pool, which allows you to customize the goroutine pool by invoking option functions to set up each configuration in `NewPool`/`NewPoolWithFunc`method.
71+
Check out [ants.Options](https://pkg.go.dev/github.com/panjf2000/ants/v2#Options) and [ants.Option](https://pkg.go.dev/github.com/panjf2000/ants/v2#Option) for more details.
24772

248-
### Customize limited pool
73+
### Customize pool capacity
24974

250-
`ants` also supports customizing the capacity of the pool. You can invoke the `NewPool` method to instantiate a pool with a given capacity, as follows:
75+
`ants` supports customizing the capacity of the pool. You can call the `NewPool` method to instantiate a `Pool` with a given capacity, as follows:
25176

25277
``` go
25378
p, _ := ants.NewPool(10000)
25479
```
25580

25681
### Submit tasks
257-
Tasks can be submitted by calling `ants.Submit(func())`
82+
Tasks can be submitted by calling `ants.Submit`
25883
```go
25984
ants.Submit(func(){})
26085
```
26186

262-
### Tune pool capacity in runtime
263-
You can tune the capacity of `ants` pool in runtime with `Tune(int)`:
87+
### Tune pool capacity at runtime
88+
You can tune the capacity of `ants` pool at runtime with `ants.Tune`:
26489

26590
``` go
26691
pool.Tune(1000) // Tune its capacity to 1000
@@ -274,11 +99,11 @@ Don't worry about the contention problems in this case, the method here is threa
27499
`ants` allows you to pre-allocate the memory of the goroutine queue in the pool, which may get a performance enhancement under some special certain circumstances such as the scenario that requires a pool with ultra-large capacity, meanwhile, each task in goroutine lasts for a long time, in this case, pre-mallocing will reduce a lot of memory allocation in goroutine queue.
275100

276101
```go
277-
// ants will pre-malloc the whole capacity of pool when you invoke this method
102+
// ants will pre-malloc the whole capacity of pool when calling ants.NewPool.
278103
p, _ := ants.NewPool(100000, ants.WithPreAlloc(true))
279104
```
280105

281-
### Release Pool
106+
### Release pool
282107

283108
```go
284109
pool.Release()
@@ -290,10 +115,10 @@ or
290115
pool.ReleaseTimeout(time.Second * 3)
291116
```
292117

293-
### Reboot Pool
118+
### Reboot pool
294119

295120
```go
296-
// A pool that has been released can be still used once you invoke the Reboot().
121+
// A pool that has been released can be still used after calling the Reboot().
297122
pool.Reboot()
298123
```
299124

0 commit comments

Comments
 (0)