Synchronously post a message to a worker_thread. Sending thread blocked, worker_thread unblocked

Issue

Is there a way to synchronously post a message to another worker_thread? In this scenario

a) the receiving thread will do async networked operations and should not be blocked
b) the sending thread should be blocked until it gets a response from the receiver

It must be a synchronous function for compatibility with a third-party library. But the function’s return value is computed from async networked operations which I have moved into another thread.

I plan to use SharedArrayBuffer and Atomics.wait in the sending thread to wait for a response. This makes sense because the sender must be blocked.

However, if I use SharedArrayBuffer instead of postMessage to send the message, then the receiving thread must use a setImmediate polling loop as opposed to waiting for a MessagePort message event. I’d rather not use Atomics.wait in the receiving thread because, ideally, it has an unblocked event loop for ongoing async operations. I’ll use polling or blocking if necessary, but ideally I can find an alternative.

Solution

Turns out, what I want to accomplish can be done entirely synchronously, and using postMessage.

Instead of using the default MessagePort created with the worker, I create my own MessageChannel and pass one of the ports to the worker when it starts. This is necessary because we need a reference to the main thread’s port later on.

Start the ports manually with .start().

When the worker needs to reply to the main thread, call .postMessage() to send the message, then use Atomics.notify() to wake up the main thread. A 4-byte SharedArrayBuffer is sufficient, since we are not transferring any data via the SharedArrayBuffer; it is only used to wake up the main thread.

In the main thread, use Atomics.wait() to wait for notification, then receiveMessageOnPort to synchronously pull the message from the port. (this is why we need a reference to the main thread’s port, mentioned above)

Answered By – cspotcode

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published