Talking without shared memory
Isolated workers cannot read each other variables, so they communicate by posting messages. One thread sends a value, the runtime delivers it to the other thread event loop as a message event. Because memory is not shared, the data must cross the thread boundary somehow.
Copy versus transfer
There are two ways the data crosses.
- Structured copy serializes the value and rebuilds an independent clone on the other side. The sender keeps its original. Simple but costs time proportional to size.
- Transfer hands ownership of a buffer to the other thread without copying. It is fast, but the sender can no longer use the transferred buffer afterward.
Transfer is ideal for large binary buffers where copying would be wasteful, while small structured data is fine to copy.
Designing the protocol
Since each message is discrete, threads agree on a simple message protocol.
- Tag messages with a type so the receiver knows how to react.
- Include a correlation id to match replies to requests.
- Keep messages small or transfer big buffers explicitly.
Key idea
Workers exchange data by posting messages that are either structured copied or ownership transferred, choosing transfer for large buffers and copy for small values, coordinated by a typed correlated protocol.