node
node copied to clipboard
worker: add connect and setConnectionsListener
This PR adds two new API to worker_threads
that allow for cross-thread communication via MessagePort
s.
A thread can invoke worker.connect
to start a new connection to another thread. This method is blocking. Upon success, the return value is a MessagePort
which can be used to exchange messages.
The core idea is that a thread willing to accept connections from other thread uses worker.setConnectionsListener
to install a callback that it is invoked with a thread id, a port and (optional) data each time another thread attempts a connection.
The listener can return true
to accept the connection. Any other return value will result in the connection being refused.
By default, if a thread has no listener associated, the connection will be refused.
Notable Change Text
A new set of experimental APIs has been added to worker_threads
: connect
and setConnectionsListener
. These APIs aim to simplify 1-1 inter-thread communication in Node.js
Every thread (including the main one) can start a connection to any another thread (including the main one) using the connect
API and providing the target threadId
.
If the connection is successful, the call will return a MessagePort
that can be used for the communication.
A thread can opt-in to receive incoming connections by calling the setConnectionsListener
API. The listener will be invoked for each connection attempt and must return true
to accept the connection. A thread without a connection listener will refused any connection by default.