github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/net/internal/queue.go (about) 1 package internal 2 3 import "sync" 4 5 // Job is a asynchronous function. 6 type Job func() error 7 8 // AsyncJobQueue queues pending tasks. 9 type AsyncJobQueue struct { 10 lock sync.Locker 11 jobs []func() error 12 } 13 14 // NewAsyncJobQueue creates a note-queue. 15 func NewAsyncJobQueue() AsyncJobQueue { 16 return AsyncJobQueue{lock: SpinLock()} 17 } 18 19 // Push pushes a item into queue. 20 func (q *AsyncJobQueue) Push(job Job) (jobsNum int) { 21 q.lock.Lock() 22 q.jobs = append(q.jobs, job) 23 jobsNum = len(q.jobs) 24 q.lock.Unlock() 25 return 26 } 27 28 // ForEach iterates this queue and executes each note with a given func. 29 func (q *AsyncJobQueue) ForEach() (err error) { 30 q.lock.Lock() 31 jobs := q.jobs 32 q.jobs = nil 33 q.lock.Unlock() 34 for i := range jobs { 35 if err = jobs[i](); err != nil { 36 return err 37 } 38 } 39 return 40 }