Skip to content

Commit

Permalink
add WaitTimeout, Option
Browse files Browse the repository at this point in the history
  • Loading branch information
icefed committed Apr 10, 2024
1 parent acb8b5a commit 90fdb71
Show file tree
Hide file tree
Showing 4 changed files with 286 additions and 78 deletions.
64 changes: 64 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package routinepool

import (
"runtime"
"time"
)

type options struct {
maxWorkers int
idleTimeout time.Duration
maxTaskSize int
}

func defaultOptions() *options {
return &options{
maxWorkers: runtime.NumCPU(),
idleTimeout: time.Second,
maxTaskSize: runtime.NumCPU(),
}
}

// Option defines pool options
type Option interface {
apply(*options)
}

type optionFunc struct {
f func(*options)
}

func (o optionFunc) apply(opts *options) {
o.f(opts)
}

// WithMaxWorkers set max worker routines, default is runtime.NumCPU().
func WithMaxWorkers(maxWorkers int) Option {
return optionFunc{func(o *options) {
if maxWorkers <= 0 {
maxWorkers = runtime.NumCPU()
}
o.maxWorkers = maxWorkers
}}
}

// WithIdleTimeout set idle timeout, default is 1s. if idle timeout is less than 1s, it will be set to 1s.
// worker routine will be closed if no task received in idle timeout. if new task received, new worker will be created.
func WithIdleTimeout(idleTimeout time.Duration) Option {
return optionFunc{func(o *options) {
if idleTimeout < time.Second {
idleTimeout = time.Second
}
o.idleTimeout = idleTimeout
}}
}

// WithMaxTaskSize set max task size, default use runtime.NumCPU().
func WithMaxTaskSize(maxTaskSize int) Option {
return optionFunc{func(o *options) {
if maxTaskSize <= 0 {
maxTaskSize = runtime.NumCPU()
}
o.maxTaskSize = maxTaskSize
}}
}
37 changes: 37 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package routinepool

import (
"runtime"
"testing"
"time"
)

func TestOptions(t *testing.T) {
o := defaultOptions()
WithMaxWorkers(10).apply(o)
if o.maxWorkers != 10 {
t.Errorf("WithMaxWorkers want 10, got %d", o.maxWorkers)
}
WithMaxWorkers(0).apply(o)
if o.maxWorkers != runtime.NumCPU() {
t.Errorf("WithMaxWorkers want %d, got %d", runtime.NumCPU(), o.maxWorkers)
}

WithIdleTimeout(time.Second * 2).apply(o)
if o.idleTimeout != time.Second*2 {
t.Errorf("WithIdleTimeout want %d, got %d", time.Second*2, o.idleTimeout)
}
WithIdleTimeout(time.Millisecond * 100).apply(o)
if o.idleTimeout != time.Second {
t.Errorf("WithIdleTimeout want %d, got %d", time.Second, o.idleTimeout)
}

WithMaxTaskSize(10).apply(o)
if o.maxTaskSize != 10 {
t.Errorf("WithMaxTaskSize want 10, got %d", o.maxTaskSize)
}
WithMaxTaskSize(0).apply(o)
if o.maxTaskSize != runtime.NumCPU() {
t.Errorf("WithMaxTaskSize want %d, got %d", runtime.NumCPU(), o.maxTaskSize)
}
}
Loading

0 comments on commit 90fdb71

Please sign in to comment.