-
Notifications
You must be signed in to change notification settings - Fork 48
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
enhance helper, db update & add worker pool util
- Loading branch information
1 parent
fed0291
commit cbb8fbc
Showing
3 changed files
with
98 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package candiutils | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
) | ||
|
||
// WorkerPool implementation | ||
type WorkerPool[T any] interface { | ||
Dispatch(ctx context.Context, jobFunc func(context.Context, T)) | ||
AddJob(job T) | ||
Finish() | ||
} | ||
|
||
type workerPool[T any] struct { | ||
maxWorker int | ||
wg sync.WaitGroup | ||
jobChan chan T | ||
} | ||
|
||
// NewWorkerPool create an instance of WorkerPool. | ||
func NewWorkerPool[T any](maxWorker int) WorkerPool[T] { | ||
wp := &workerPool[T]{ | ||
maxWorker: maxWorker, | ||
wg: sync.WaitGroup{}, | ||
jobChan: make(chan T), | ||
} | ||
|
||
return wp | ||
} | ||
|
||
func (wp *workerPool[T]) Dispatch(ctx context.Context, jobFunc func(context.Context, T)) { | ||
for i := 0; i < wp.maxWorker; i++ { | ||
go func(jobFunc func(context.Context, T)) { | ||
for job := range wp.jobChan { | ||
jobFunc(ctx, job) | ||
wp.wg.Done() | ||
} | ||
}(jobFunc) | ||
} | ||
} | ||
|
||
func (wp *workerPool[T]) AddJob(job T) { | ||
wp.wg.Add(1) | ||
wp.jobChan <- job | ||
} | ||
|
||
func (wp *workerPool[T]) Finish() { | ||
close(wp.jobChan) | ||
wp.wg.Wait() | ||
} |