16 Sharing resources between timelines

In this chapter
- Learn how to diagnose bugs due to sharing resources.
- Understand how to create a resource-sharing primitive that can allow resources to be shared safely.
In the last chapter, we learned about timelines and how to reduce the number of resources they share. Timelines that don’t share any resources are ideal, but sometimes you need to share resources. In that case, you need to make sure they share them in a safe way. In this chapter, we will see how we can create reusable pieces of code called concurrency primitives that will let us share resources.
Principles of working with timelines
Here are the principles again as a reminder. In the last chapter, we worked through principles 1–3, showing how they help ensure correctness. In this chapter, we will be applying principle 4. We have a resource that is shared between timelines, and we’ll build a reusable way to coordinate the timelines so they share it safely.
1. Fewer timelines are easier
Every new timeline dramatically makes the system harder to understand. If we can reduce the number of timelines (t in the formula on the right), it will help tremendously. Unfortunately, we often can’t control how many timelines we have.
2. Shorter timelines are easier
If we can eliminate steps in our timelines (decrease a in the formula on the right), we can reduce the number of possible orderings dramatically.
3. Sharing fewer resources is easier