@@ -2,6 +2,7 @@ package pool
2
2
3
3
import (
4
4
"context"
5
+ "sync"
5
6
"time"
6
7
7
8
"golang.org/x/sync/errgroup"
62
63
stats * safeStats
63
64
64
65
spawnCancel context.CancelFunc
66
+
67
+ wg * sync.WaitGroup
65
68
}
66
69
option [PT Item [T ], T any ] func (p * Pool [PT , T ])
67
70
)
@@ -205,7 +208,9 @@ func New[PT Item[T], T any](
205
208
}
206
209
207
210
var spawnCtx context.Context
211
+ p .wg = & sync.WaitGroup {}
208
212
spawnCtx , p .spawnCancel = xcontext .WithCancel (xcontext .ValueOnly (ctx ))
213
+ p .wg .Add (1 )
209
214
go p .spawnItems (spawnCtx )
210
215
211
216
return p
@@ -215,13 +220,17 @@ func New[PT Item[T], T any](
215
220
// It ensures that pool would always have amount of connections equal to configured limit.
216
221
// If item creation ended with error it will be retried infinity with configured interval until success.
217
222
func (p * Pool [PT , T ]) spawnItems (ctx context.Context ) {
223
+ defer p .wg .Done ()
218
224
for {
219
225
select {
226
+ case <- ctx .Done ():
227
+ return
220
228
case <- p .done :
221
229
return
222
230
case <- p .itemTokens :
223
231
// got token, must create item
224
232
for {
233
+ p .wg .Add (1 )
225
234
err := p .trySpawn (ctx )
226
235
if err == nil {
227
236
break
@@ -234,12 +243,15 @@ func (p *Pool[PT, T]) spawnItems(ctx context.Context) {
234
243
}
235
244
236
245
func (p * Pool [PT , T ]) trySpawn (ctx context.Context ) error {
246
+ defer p .wg .Done ()
237
247
item , err := p .createItem (ctx )
238
248
if err != nil {
239
249
return err
240
250
}
241
251
// item was created successfully, put it in queue
242
252
select {
253
+ case <- ctx .Done ():
254
+ return ctx .Err ()
243
255
case <- p .done :
244
256
return nil
245
257
case p .queue <- item :
@@ -523,6 +535,9 @@ func (p *Pool[PT, T]) Close(ctx context.Context) (finalErr error) {
523
535
// Due to multiple senders queue is not closed here,
524
536
// we're just making sure to drain it fully to close any existing item.
525
537
close (p .done )
538
+
539
+ p .wg .Wait ()
540
+
526
541
var g errgroup.Group
527
542
shutdownLoop:
528
543
for {
0 commit comments