Blocking/Async Function Calls
* A system's API contains async functions.
Otherwise, you get the [_Callback Hell_](https://en.wiktionary.org/wiki/callback_hell)
which is JavaScript before all the async extensions.
* This pattern is based upon the _[Multi-Threaded Synchronization](multi-threading.md)_ pattern.
* An independent thread is used to run the scripting [`Engine`].
* An MPSC channel (or any other appropriate synchronization primitive) is used to send function call
arguments, packaged as a message, to another Rust thread that will perform the actual async calls.
* Results are marshaled back to the [`Engine`] thread via another MPSC channel.
See the _[Multi-Threaded Synchronization](multi-threading.md)_ pattern.
Implementation
-
Spawn a thread to run the scripting
Engine
. Usually thesync
feature is NOT used for this pattern. -
Spawn another thread (the
worker
thread) that can perform the actual async calls in Rust. This thread may actually be the main thread of the program. -
Create a pair of MPSC channels (named
command
andreply
below) for full-duplex communications between the two threads. -
Register async API function to the
Engine
with a closure that captures the MPSC end-points. -
If there are more than one async function, the receive end-point on the
reply
channel can simply be cloned. The send end-point on thecommand
channel can be wrapped in anArc<Mutex<Channel>>
for shared access. -
In the async function, the name of the function and call arguments are serialized into JSON (or any appropriate message format) and sent to
command
channel, where they’ll be removed by theworker
thread and the appropriate async function called. -
The
Engine
blocks on the function call, waiting for a reply message on thereply
channel. -
When the async function call complete on the
worker
thread, the result is sent back to theEngine
thread via thereply
channel. -
After the result is obtained from the
reply
channel, theEngine
returns it as the return value of the function call, ending the block and continuing evaluation.