rogchap / v8go

Execute JavaScript from Go

Home Page:https://rogchap.com/v8go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

example for terminating scripts should have a warning about accessing isolates from other threads

tkp-richard opened this issue · comments

vals := make(chan *v8.Value, 1)
errs := make(chan error, 1)

go func() {
    val, err := ctx.RunScript(script, "forever.js") // exec a long running script
    if err != nil {
        errs <- err
        return
    }
    vals <- val
}()

select {
case val := <- vals:
    // success
case err := <- errs:
    // javascript error
case <- time.After(200 * time.Milliseconds):
    vm := ctx.Isolate() // get the Isolate from the context
    vm.TerminateExecution() // terminate the execution
    err := <- errs // will get a termination error back from the running script
}

i wanted to implement a memory limit for the isolate. so i implemented a ticker to check the limit with GetHeapStatistics. following this example, i called RunScript in a goroutine, and the terminate in the main routine. this caused fatal errors which i assume is because of this.

// NewIsolate creates a new V8 isolate. Only one thread may access
// a given isolate at a time, but different threads may access
// different isolates simultaneously.

i think the example should be refactored to have the TerminateExecution in a goroutine instead, or have a comment to warn about the usage.