Concurrency P2: Mayday mayday, entering the critical section

12 Sep 2018

Welcome back! Do you remember what we discussed in the last post? We talked about what concurrency fundamentally is and what a thread is. In this post, we’re going to expand on that and get some more terminology in.

Now that we know threads are awesome and super useful, it’s time to dive into the bits that makes it difficult to work with many of them. The problem with having many threads arises when you have more than one thread using the same resource. I imagine it being like a public bathroom where there are no locks on the doors, a bunch of people walking in on each other with their pants down, leading to overall chaos and embarrassment. Now this analogy is far from perfect, but hopefully you get the idea. In fact threads have no care in the world about other threads needing the value of variable they just changed. What we really want to avoid is this type of situation, where two or more threads try to access shared data and change it at the same time. This is also known as a Race Condition.

Race conditions are a problem because we have no way of knowing the order in which the threads execute. This up to something called a thread scheduler, who decides which thread get to run and for how long.

We have to make sure each thread doesn’t try to access shared data at the same time. But running threads in their entirety sequentially makes lose their value, we could just run a sequential program instead. Therefore, we need to identify the area of the code that is actually using shared data. This area is called the critical section. When a thread is in it’s critical section it should have sole access to the shared data, so it can do it’s operations and leave the data in a consistent state. Where a consistent state is one where the data has changed in the way the one thread instructed it to.

This principle is called mutual exclusion and it forms the basis of dealing with shared data. More formally mutual exclusion means that no threads sharing the same resource should be in their critical section at the same time. This is what we’ll be looking into in the next blog post.

Mutual exclusion

-----------------------------------------------------------------