Skip to content

Commit

Permalink
Panic instead of returning an error when pool size is invalid.
Browse files Browse the repository at this point in the history
  • Loading branch information
sherifabdlnaby committed Dec 14, 2019
1 parent 95ca4c0 commit eda9379
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions gpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var (
)

const (
poolClosed = iota
poolStopped = iota
poolStarted
)

Expand All @@ -32,20 +32,23 @@ type Pool struct {

// NewPool returns a pool that uses semaphore implementation.
// Returns ErrPoolInvalidSize if size is < 1.
func NewPool(size int) (*Pool, error) {
func NewPool(size int) *Pool {

if size < 1 {
return nil, ErrPoolInvalidSize
panic(ErrPoolInvalidSize)
return nil
}

newWorkerPool := Pool{
workerCount: size,
semaphore: semaphore.NewWeighted(math.MaxInt64),
mu: sync.Mutex{},
status: poolClosed,
status: poolStopped,
}

return &newWorkerPool, nil
newWorkerPool.Start()

return &newWorkerPool
}

// Start the Pool, otherwise it will not accept any job.
Expand Down Expand Up @@ -73,15 +76,15 @@ func (w *Pool) Stop() {
w.mu.Lock()
defer w.mu.Unlock()

if w.status == poolClosed {
if w.status == poolStopped {
return
}

// Try to Acquire the whole Semaphore ( This will block until all ACTIVE works are done )
// And also plays as a lock to change pool status.
_ = w.semaphore.Acquire(context.Background(), int64(w.workerCount))

w.status = poolClosed
w.status = poolStopped

// Release the Semaphore so that subsequent enqueues will not block and return ErrPoolClosed.
w.semaphore.Release(int64(w.workerCount))
Expand All @@ -92,9 +95,9 @@ func (w *Pool) Stop() {
// Resize the pool size in concurrent-safe way.
//
// `Resize` can enlarge the pool and any blocked enqueue will unblock after pool is resized, in case of shrinking the pool `resize` will not affect any already processing job.
func (w *Pool) Resize(newSize int) error {
func (w *Pool) Resize(newSize int) {
if newSize < 1 {
return ErrPoolInvalidSize
panic(ErrPoolInvalidSize)
}

// Resize
Expand All @@ -108,8 +111,6 @@ func (w *Pool) Resize(newSize int) error {
}

w.mu.Unlock()

return nil
}

// Enqueue Process job `func(){...}` and returns ONCE the func has started executing (not after it ends/return)
Expand Down

0 comments on commit eda9379

Please sign in to comment.