Skip to content

Commit

Permalink
Merge pull request #5 from shmel1k/feature/add_context
Browse files Browse the repository at this point in the history
[pool] add AddContext functionality without tests
  • Loading branch information
shmel1k authored Apr 29, 2020
2 parents ebe0f03 + 16b3a9f commit fe097c6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
module github.com/shmel1k/gop

go 1.13
15 changes: 13 additions & 2 deletions pool.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gop

import (
"context"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -58,13 +59,19 @@ func NewPool(conf Config) *Pool {

// Add adds tasks to the pool.
func (p *Pool) Add(t TaskFn) error {
return p.add(t)
return p.add(context.Background(), t)
}

func (p *Pool) add(t TaskFn) error {
func (p *Pool) AddContext(ctx context.Context, t TaskFn) error {
return p.add(ctx, t)
}

func (p *Pool) add(ctx context.Context, t TaskFn) error {
select {
case <-p.quit:
return ErrPoolClosed
case <-ctx.Done():
return ctx.Err()
default:
}

Expand All @@ -80,6 +87,8 @@ func (p *Pool) add(t TaskFn) error {
case p.tasks <- t:
atomic.AddInt32(&p.realQueueSize, 1)
return nil
case <-ctx.Done():
return ctx.Err()
default:
}

Expand All @@ -105,6 +114,8 @@ func (p *Pool) add(t TaskFn) error {
return nil
case <-p.quit:
return ErrPoolClosed
case <-ctx.Done():
return ctx.Err()
case <-time.After(left):
// Wait till task scheduling drops by timeout.
return ErrScheduleTimeout
Expand Down

0 comments on commit fe097c6

Please sign in to comment.