2020-09-21 09:49:33 +00:00
|
|
|
package util
|
|
|
|
|
2021-10-12 11:55:49 +00:00
|
|
|
import (
|
2023-05-19 15:06:20 +00:00
|
|
|
"sync/atomic"
|
|
|
|
|
2021-10-12 11:55:49 +00:00
|
|
|
"github.com/panjf2000/ants/v2"
|
|
|
|
)
|
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// WorkerPool represents a tool to control
|
2020-09-21 09:49:33 +00:00
|
|
|
// the execution of go-routine pool.
|
|
|
|
type WorkerPool interface {
|
|
|
|
// Submit queues a function for execution
|
|
|
|
// in a separate routine.
|
|
|
|
//
|
|
|
|
// Implementation must return any error encountered
|
|
|
|
// that prevented the function from being queued.
|
|
|
|
Submit(func()) error
|
2021-10-12 11:55:49 +00:00
|
|
|
|
|
|
|
// Release releases worker pool resources. All `Submit` calls will
|
|
|
|
// finish with ErrPoolClosed. It doesn't wait until all submitted
|
|
|
|
// functions have returned so synchronization must be achieved
|
|
|
|
// via other means (e.g. sync.WaitGroup).
|
|
|
|
Release()
|
2020-09-21 09:49:33 +00:00
|
|
|
}
|
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// pseudoWorkerPool represents a pseudo worker pool which executes the submitted job immediately in the caller's routine.
|
2021-10-12 11:55:49 +00:00
|
|
|
type pseudoWorkerPool struct {
|
|
|
|
closed atomic.Bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// ErrPoolClosed is returned when submitting task to a closed pool.
|
|
|
|
var ErrPoolClosed = ants.ErrPoolClosed
|
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// NewPseudoWorkerPool returns a new instance of a synchronous worker pool.
|
2021-10-12 11:55:49 +00:00
|
|
|
func NewPseudoWorkerPool() WorkerPool {
|
|
|
|
return &pseudoWorkerPool{}
|
|
|
|
}
|
2020-09-21 09:49:33 +00:00
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// Submit executes the passed function immediately.
|
2020-09-21 09:49:33 +00:00
|
|
|
//
|
|
|
|
// Always returns nil.
|
2021-10-12 11:55:49 +00:00
|
|
|
func (p *pseudoWorkerPool) Submit(fn func()) error {
|
|
|
|
if p.closed.Load() {
|
|
|
|
return ErrPoolClosed
|
|
|
|
}
|
|
|
|
|
2020-09-21 09:49:33 +00:00
|
|
|
fn()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2021-10-12 11:55:49 +00:00
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// Release implements the WorkerPool interface.
|
2021-10-12 11:55:49 +00:00
|
|
|
func (p *pseudoWorkerPool) Release() {
|
|
|
|
p.closed.Store(true)
|
|
|
|
}
|