59 lines
901 B
Go
59 lines
901 B
Go
package jobm
|
|
|
|
import (
|
|
"runtime"
|
|
"sync"
|
|
|
|
"gitbase.de/apairon/mark2web/pkg/logger"
|
|
)
|
|
|
|
var wg sync.WaitGroup
|
|
var numCPU = runtime.NumCPU()
|
|
|
|
// Job is a wrapper to descripe a Job function
|
|
type Job struct {
|
|
Function func()
|
|
Description string
|
|
Category string
|
|
}
|
|
|
|
var jobChan = make(chan Job)
|
|
|
|
func worker(jobChan <-chan Job) {
|
|
defer wg.Done()
|
|
|
|
for job := range jobChan {
|
|
job.Function()
|
|
}
|
|
}
|
|
|
|
func init() {
|
|
logger.Log.Infof("number of CPU core: %d", numCPU)
|
|
// one core for main thread
|
|
for i := 0; i < (numCPU - 1); i++ {
|
|
wg.Add(1)
|
|
go worker(jobChan)
|
|
}
|
|
}
|
|
|
|
// Enqueue enqueues a job to the job queue
|
|
func Enqueue(job Job) {
|
|
if numCPU <= 1 {
|
|
// no threading
|
|
job.Function()
|
|
return
|
|
}
|
|
jobChan <- job
|
|
}
|
|
|
|
// Wait will wait for all jobs to finish
|
|
func Wait() {
|
|
close(jobChan)
|
|
wg.Wait()
|
|
}
|
|
|
|
// SetNumCPU is for testing package without threading
|
|
func SetNumCPU(i int) {
|
|
numCPU = i
|
|
}
|