emscripten-core / emscripten

Emscripten: An LLVM-to-WebAssembly Compiler
Other
25.79k stars 3.3k forks source link

Opencv.js --threads how to compleatly release memory when refreshing page? #21341

Open Jove125 opened 8 months ago

Jove125 commented 8 months ago

Hi,

How to completely release memory when an application terminates? For example, when refreshing a page or moving to the another page?

The error (not enough memory) only occurs when refreshing a page with the multi-threaded version of opencv (build with --threads flag) and does not occurs with the single-threaded version. And only on devices with 3 GB of RAM.

I tried release memory like this, but it didn't help:

window.onbeforeunload = function()
{
    if (cv.PThread !== undefined)
    {
        cv.PThread.terminateAllThreads();
        cv.__emscripten_thread_free_data();
    }
}

It seems that the memory is not release or it does not release immediately on page refresh. Therefore, when opening the application again in the same tab, an error occurs.

P.S. I had exactly the same error with Tensorflow.js. It was successfully resolved after memory was released on the window.onbeforeunload event. There the memory release function looks like this:

TFLiteWebModelRunner.prototype.cleanUp=function()
{
    if(null!=this.cppClassifier)
    {
        for(var a=$jscomp.makeIterator(this.memOffsetsToFree),b=a.next();!b.done;b=a.next())
            this.module._free(b.value);
            this.cppClassifier.delete()
    }
};

Is there the same function in opencv.js? Is there a way to simply reset the wasm memory when the application terminates?

sbc100 commented 8 months ago

I'm not sure there is anything we can here since then you close a tab of refresh a page I think its up the browser to completely free everything on that page, including the workers.

@kripken is that your understanding too? Or is there something more we can do here? @RReverser might have some ideas too.

RReverser commented 8 months ago

Yeah it should be completely freed, otherwise it's a specific browser's bug and worth reporting there. That said, I remember @juj running into similar bug with memory not being released properly when using threads, maybe they can chime in.

juj commented 8 months ago

I recall seeing memory unloading related problems in Chrome when I was investigating trouble around this issue: https://github.com/WebAssembly/threads/issues/176 . Though iirc that issue did get fixed in Chrome. (could not find the bug report in Chrome right now)

If you are seeing issues, I recommend trying to reduce the issue in a small test case, where you repeatedly alloc tabs until leaking, and then report it up to Chrome browsers to look?