summaryrefslogtreecommitdiff
path: root/pkg/worker_watcher/container/vec.go
blob: 1ab9d07358801e27d6f91a6e303ddfce23ed5b78 (plain)
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
package container

import (
	"sync/atomic"

	"github.com/spiral/roadrunner/v2/pkg/worker"
)

type Vec struct {
	wqLen   uint64
	destroy uint64
	workers chan worker.BaseProcess
}

func NewVector(initialNumOfWorkers uint64) Vector {
	vec := &Vec{
		wqLen:   0,
		destroy: 0,
		workers: make(chan worker.BaseProcess, initialNumOfWorkers),
	}

	return vec
}

func (v *Vec) Enqueue(w worker.BaseProcess) {
	atomic.AddUint64(&v.wqLen, 1)
	v.workers <- w
}

func (v *Vec) Dequeue() (worker.BaseProcess, bool) {
	/*
		if *addr == old {
			*addr = new
			return true
		}
	*/

	if atomic.CompareAndSwapUint64(&v.destroy, 1, 1) {
		return nil, true
	}

	if num := atomic.LoadUint64(&v.wqLen); num > 0 {
		atomic.AddUint64(&v.wqLen, ^uint64(0))
		return <-v.workers, false
	}

	return nil, false
}

func (v *Vec) Destroy() {
	atomic.StoreUint64(&v.destroy, 1)
}