summaryrefslogtreecommitdiff
path: root/engine/CoreObjects/Balancer.go
blob: 0e80b1008e3e6067f6a3db60ce66e8ad6fbd103f (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package coreobjects

import (
	"sync"

	settings "github.com/DegustatorPonos/RuinesOfRafdolon/Settings"
)

type runner struct {
	ExecChan chan UpdateFunction
	CompleteChan chan any
}

func makeRunner(execChan chan UpdateFunction, completeChan chan any) *runner {
	var outp = &runner {
		ExecChan: execChan,
		CompleteChan: completeChan,
	}
	outp.Init()
	return outp
}

func (base *runner) Init()  { 
	go func() {
		for {
			var task = <- base.ExecChan
			task()
			base.CompleteChan <- nil
		}
	}()
}

// Balances the updates so that the execution of WASM doesn't clog the system
type balancer struct {
	MaxRoutines int
	// So that we don't use invloke balancer twice
	mut *sync.Mutex
	Runners []*runner
	// balancer -> 
	ExecChan chan UpdateFunction
	CompleteChan chan any
}

func makeBalancer() *balancer {
	var maxRoutines = settings.Current.MaxUpdateRoutines
	var outp = &balancer{
		MaxRoutines: maxRoutines,
		mut: &sync.Mutex{},
		Runners: make([]*runner, maxRoutines),
		ExecChan: make(chan UpdateFunction, maxRoutines),
		CompleteChan: make(chan any, maxRoutines),
	}
	for i := range maxRoutines {
		outp.Runners[i] = makeRunner(outp.ExecChan, outp.CompleteChan)
	}
	return outp
}

func (base *balancer) Execute(tasks []UpdateFunction) {
	base.mut.Lock()
	defer base.mut.Unlock()
	for _, v := range tasks {
		base.ExecChan <- v
	}

	// Sync
	var results = 0
	for {
		<- base.CompleteChan
		results++
		if results == len(tasks) {
			break
		}
	}
}