diff options
Diffstat (limited to 'engine/CoreObjects/Balancer.go')
| -rw-r--r-- | engine/CoreObjects/Balancer.go | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/engine/CoreObjects/Balancer.go b/engine/CoreObjects/Balancer.go new file mode 100644 index 0000000..0e80b10 --- /dev/null +++ b/engine/CoreObjects/Balancer.go @@ -0,0 +1,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 + } + } +} |
