首页 > 解决方案 > 我正在运行一个受 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 的开发状态的文章,看起来多线程工作负载还不是很普遍。

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

标签: goweb-workerwebassembly

解决方案


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

你可能已经找到了:


推荐阅读