Mutex – Process Synchronization

Process synchronization refers to the idea that multiple process can manipulate a single portion of data. Take for example a pthread, which you can think of as a single core on your computer. That core has access to all of the data stored in RAM, however you may have multiple cores running. What happens if you are trying to watch a video and at the same time another program is attempting to edit said video. This would create a problem for the computer, one person is trying to watch it and at one moment the data could be there, and the next it can be deleted. Have you ever seen one of those warning claiming “This process/app is in use, cannot delete.” This is your operating system telling you that it is not safe to delete that item.

Why do we care?

Process synchronization is one of the most important tasks of any program/operating system. Imagine a world where you cannot insure that something is deleted while you are working on it. That would be awful. This is why process synchronization is important and often is heavily covered in any systems course.

The Basics

Critical Section – A critical section is a portion of code or a process that cannot be run on multiple threads at the same time, take for example a program which processes bank transactions. It would be silly to allow multiple threads to access transaction data, image if to threads simultaneously attempted to add $1000 to an account. This can happen since threads are not guaranteed to run in any particular order. To solve this, we must find a way to declare a portion of a process “critical” meaning it cannot be done on multiple threads (or in parallel) at the same time.

A Mutex solves this problem, the name is short for “Mutual Exclusion” and is a structure used to ensure that only one thread has access to a critical section at a given time. You can think of a mutex as a stop light of sorts, where only one lane gets a green light to go at a given time. You can give a thread the “green light” when a thread is unlocked and a “red light” when a mutex is locked, here is an example from

The output:


The fact that the critical section was locked prevented printing a mixture of different characters, which would be in some random order if the mutex was unlocked. The th1.join() and th2.join you see at the bottom simply joins the threads back to the main thread, closing the th1 and th2 thread.

Leave a Reply

Your email address will not be published. Required fields are marked *

 characters available

Time limit is exhausted. Please reload the CAPTCHA.