【问题标题】:I am running a CPU-bound WASM function. How do I prevent it from blocking the UI thread?我正在运行受 CPU 限制的 WASM 函数。如何防止它阻塞 UI 线程?
【发布时间】: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


【解决方案1】:

是的,我想你自己回答了这个问题。只要 WASM 本身不支持像 lite-threads / concurrency 之类的东西(这将使 Go 对 WASM 的支持更具吸引力),你就会被困在自己使用 web-workers 或基于 web-workers 的包中。

你可能已经找到了:

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多