我有以下go-duktape代码:
package main
import (
"fmt"
"gopkg.in/olebedev/go-duktape.v3"
"time"
)
func main() {
code := "function test(){log('testing');log('testing2');done();done();};"
resp := make(chan string)
ctx := duktape.New()
go doExec(code, ctx, resp)
select {
case r := <-resp:
fmt.Printf("%s\n", r)
case <-time.After(5 * time.Second):
fmt.Printf("Execution timeout\n")
}
kill(ctx)
close(resp)
}
func kill(ctx *duktape.Context) {
ctx.DestroyHeap()
ctx.Destroy()
}
func doExec(code string, ctx *duktape.Context, resp chan string) {
ctx.PushGlobalGoFunction("done", func(c *duktape.Context) int {
resp <- "We're done!!"
return 0
})
ctx.PushGlobalGoFunction("log", func(c *duktape.Context) int {
fmt.Println(c.SafeToString(-1))
return 0
})
err := ctx.PevalString(code + ";try{test()}catch(e){log('Error in execution');}")
if err != nil {
fmt.Printf("Error is %s\n", err.Error())
resp <- "Error in exec"
}
}
我的目标是在 FIRST done()
函数调用之后终止程序,并且在此之后不再执行任何功能。但是,如果我运行以下代码,它会出现紧急情况,因为done()
被调用了两次,而第二个调用试图在关闭的通道上写入。如何确保它在第一次done()
调用之后终止?
谢谢!