The future pattern, also known as a promise, can be simply described as a function that runs in the background thread. The basic usage pattern is intentionally very simple:
- The main thread creates a future (starts a calculation in another thread).
- The main thread does some other work.
- The main thread reads the result of the future (reads the result of the calculation). If the calculation is not finished yet, the main thread blocks until the result is available.
The future pattern allows the program to execute multiple tasks in parallel while it neatly encapsulates the background calculation in a separate function. It also provides a simple way of re-synchronization between two threads when the result of calculation is required.
In a kitchen, the chef asks their assistant to cut up a few onions. While the assistant peels, cuts, and cries, the chef continues preparing other...