【发布时间】:2021-01-02 06:29:44
【问题描述】:
我在 .wasm 文件中公开了一个 Go 函数,可以从 JS 访问:
app.computePrimes = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
resolve := args[0]
// Commented out because this Promise never fails
//reject := args[1]
// Now that we have a way to return the response to JS, spawn a goroutine
// This way, we don't block the event loop and avoid a deadlock
go func() {
app.console.Call("log", "starting")
for i := 2; i < 100000; i++ {
if big.NewInt(int64(i)).ProbablyPrime(20) && i > 20000 {
app.console.Call("log", i)
}
}
app.console.Call("log", "finishing")
resolve.Invoke("Done")
}()
// The handler of a Promise doesn't return any value
return nil
})
return js.Global().Get("Promise").New(handler)
})
尽管它返回一个 Promise 并在 goroutine 中执行 CPU 绑定部分,但在 Web 端,感觉就像一切都在主 UI 线程上运行。我读过一些关于 WWebAssembly 的开发状态,似乎多线程工作负载还不是很普遍。
网络工作者是执行此类任务的唯一首选方式吗?
【问题讨论】:
-
我不确定 Go/WASM 是如何工作的,但如果我记得,在 GopherJS 中的这种情况下,在紧密循环中添加断点以允许 Go 运行时可能很有用调度程序有机会执行其他代码。虽然如果你的整个应用程序不是用 Go/WASM 编写的,这可能没有多大帮助。
标签: go web-worker webassembly