zq.go 1.21 KB
Newer Older
Vladimir Barsukov's avatar
zgo  
Vladimir Barsukov committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package zq

import (
	"git.barsukov.pro/barsukov/zgo/zatomic"
	"git.barsukov.pro/barsukov/zgo/zwg"
)

type ZQ struct {
	WorkerCounter *zatomic.Int
	WorkerFn      func(any)
	JobsWg        *zwg.Zwg

	complete chan bool
	jobs     chan any
}

func New(qtyWorkers int, w func(any)) *ZQ {
	q := &ZQ{
		WorkerCounter: zatomic.New(),
		WorkerFn:      w,
		JobsWg:        zwg.New(),
		jobs:          make(chan any),
		complete:      make(chan bool),
	}

	for i := 0; i < qtyWorkers; i++ {
		q.AddWorker(1)
	}

	return q
}

func (q *ZQ) AddWorker(delta int) {
	if delta < 1 {
		for i := 0; i < delta*-1; i++ {
			q.complete <- true
		}

		return
	}

	for i := 0; i < delta; i++ {
		q.WorkerCounter.Add(1)

		go func() {
			defer q.WorkerCounter.Add(-1)

			for {
				select {
				case <-q.complete:
					return
				case j := <-q.jobs:
					q.WorkerFn(j)
					q.JobsWg.Done()
				}
			}
		}()
	}
}

func (q *ZQ) RemoveWorker() {
	q.AddWorker(-1)
}

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
65
func (q *ZQ) AddJob(a any) *ZQ {
Vladimir Barsukov's avatar
zgo  
Vladimir Barsukov committed
66
67
68
69
70
	q.JobsWg.Inc()

	go func() {
		q.jobs <- a
	}()
Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
71
72

	return q
Vladimir Barsukov's avatar
zgo  
Vladimir Barsukov committed
73
74
}

Vladimir Barsukov's avatar
zgo    
Vladimir Barsukov committed
75
76
77
78
79
80
81
func (q *ZQ) AddJobSync(a any) *ZQ {
	q.JobsWg.Inc()
	q.jobs <- a

	return q
}

Vladimir Barsukov's avatar
zgo  
Vladimir Barsukov committed
82
83
84
85
86
87
88
89
func (q *ZQ) Wait() {
	q.JobsWg.Wait()
}

func (q *ZQ) Quit() {
	q.Wait()
	q.AddWorker(q.WorkerCounter.LoadInverse())
}