package jsvm
import (
"sync"
"github.com/dop251/goja"
)
type poolItem struct {
mux sync.Mutex
busy bool
vm *goja.Runtime
}
type vmsPool struct {
mux sync.RWMutex
factory func() *goja.Runtime
items []*poolItem
}
func newPool(size int, factory func() *goja.Runtime) *vmsPool {
if size < 0 {
size = 0
}
pool := &vmsPool{
factory: factory,
items: make([]*poolItem, size),
}
for i := 0; i < size; i++ {
vm := pool.factory()
pool.items[i] = &poolItem{vm: vm}
}
return pool
}
func (p *vmsPool) run(call func(vm *goja.Runtime) error) error {
p.mux.RLock()
var freeItem *poolItem
for _, item := range p.items {
item.mux.Lock()
if item.busy {
item.mux.Unlock()
continue
}
item.busy = true
item.mux.Unlock()
freeItem = item
break
}
p.mux.RUnlock()
if freeItem == nil {
return call(p.factory())
}
execErr := call(freeItem.vm)
freeItem.mux.Lock()
freeItem.busy = false
freeItem.mux.Unlock()
return execErr
}