Search code examples
javascriptmultithreadingweb-worker

What will happen if the main thread is busy when a worker thread posts a message?


I have a situation where the worker thread parse some data and send the parsed result to main thread using postMessage. And then the worker thread continue to parse more data. So we can say, the worker thread is like a loop where after each loop, it sends some data to the main thread.

In the main thread, i do some look up in a global array to check if the received data already exists. If it doesn't, then i insert the data in the array. While i do this, the worker thread continues to parse data and send it to main thread.

The lookup can be quite expensive and time consuming.

Now my problem is, it crashes in every browser. But if i remove the look up from the main thread and just insert the data into the global array, it works fine. So i am assuming the crash is happening because the main thread stays busy when the second postMessage is called from the worker.

My question is two fold -

1) Am i correct in my analysis? I mean, is it possible to crash if the main thread is busy when a postMessage is called from the working thread?

2) Is there any way to overcome this situation?


Solution

  • 1) Am i correct in my analysis?

    Not really, no. JavaScript works via a job queue (HTML5 calls it a task queue). All that happens if your worker posts a message to your main UI thread is that a call to the message handler is added to the queue. If the main thread is busy with a previous job, it will complete that job and then check the queue for another job.

    If your code is "crashing" the browser, it means the main thread is working very hard, starving the browser of thread time to update the UI, etc.

    I said "not really" because it sounds like what's happening is that the main thread can't keep up, which is similar to (but not the same) as what you thought was happening.

    2) Is there any way to overcome this situation?

    Fundamentally, shift more of the work to the worker (or another worker) and away from the main thread. But without code, we can't really help you with that.

    If you're doing intense calculations and such, you want to use the main thread only for updating the UI, and keep everything else in a worker thread or two (at most).