rogchap / v8go

Execute JavaScript from Go
https://rogchap.com/v8go
BSD 3-Clause "New" or "Revised" License
3.22k stars 221 forks source link

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

Open tkp-richard opened 2 years ago

tkp-richard commented 2 years ago
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.