There are three main methods here:
- Message passing
- Capturing
- Shared state
Capturing
The body of the closure function can reference variables declared outside of the anonymous function scope in the context where the closure was called. We may need to do things like borrow variables in languages like rust to make this happen. We use this a lot in algorithmic problems in python and GoLang, when we define a function within a function.
Message Passing
This is akin to pipes and Message Queues. This is safer than shared memory. The standard model for message passing is using a channel with a transmit end and a receive end where this is a Producer Consumer Model. Lots of threads can produce, but the data can only end up in one place. You relinquish ownership when you pass data.
If you want multiple transmitting ends, you need to clone the transmitter and hand out the clones.