我正在运行一个CPU绑定的WASM函数.如何防止它阻塞UI线程



我有一个在.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开发状态的文章,多线程工作负载似乎还不常见。

Web工作者是执行此类任务的唯一首选方式吗?

是的,我想你自己回答了这个问题。只要WASM本身不支持lite线程/并发性之类的东西(这将使Go对WASM的支持更具吸引力(,您就有点陷入了使用web工作者或基于web工作者的包来自己做这件事的困境。

你可能已经找到了:

  • https://pspdfkit.com/blog/2020/webassembly-in-a-web-worker/
  • https://www.sitepen.com/blog/using-webassembly-with-web-workers

最新更新