go - 我正在运行一个受 CPU 限制的 WASM 函数。如何防止它阻塞 UI 线程?
问题描述
我在文件中公开了一个 Go 函数.wasm
,可以从 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 的开发状态的文章,看起来多线程工作负载还不是很普遍。
网络工作者是执行此类任务的唯一首选方式吗?
解决方案
是的,我想你自己回答了这个问题。只要 WASM 本身不支持像 lite-threads / concurrency 之类的东西(这将使 Go 对 WASM 的支持更具吸引力),你就会被困在自己使用 web-workers 或基于 web-workers 的包中。
你可能已经找到了:
推荐阅读
- javascript - 可以在javascript中的任何返回函数上使用promise吗?
- javascript - 除非我将日期作为字符串传递,否则 Moment.js 时区不会转换
- stored-procedures - 为多个表中的大量插入和更新维护事务
- java - 使第一个输入先保存在文件夹中,然后引用它
- node.js - 使用 Fetch-node.buffer() 在 Node 中下载二进制文件 - 文件未正确解码
- linux - Linux perf 记录未生成任何样本
- ios - CallKit CXEndCallAction 向另一端报告 - Swift
- r - 生存竞争风险 Cox 模型
- scala - Scala:如何制作多种方法并一一应用?
- docker - 无法在云提供商上部署我的应用