Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C++

Between Mutex, Semaphore and Horrible Hairdos

Rate me:
Please Sign up or sign in to vote.
4.91/5 (7 votes)
28 Oct 2022CPOL5 min read 4K   3   1
Mutex or Semaphores are here to offer non-recursive semantics, so your program, or chunks of your code will only run once — no hairspray needed...
Back in the jolly days of horrible hairdos, it was possible to run several instances of a program repeatedly on a single machine: multiple windows were opened one on top of each other endlessly. Today, in most cases, we want to make sure our program runs once per machine. Mutex or Semaphores are here to offer non-recursive semantics, so your program will only run once — no hairspray needed.

Image 1

Introduction

Mutex and Semaphores, Semaphores and Mutex — Though both names sound a bit like something your doctor might prescribe, mutex and semaphores are two fundamental concepts in computer programming. But before we explain what these concepts are, let us start at the beginning — and when we say “the beginning” we mean the early days of computer programs: the days of horrible hairdos, tons of hairspray and a thinning ozone.

You might know, or, if you are an old timer, even recall, that back in the jolly days of the 80s and early 90s, it was possible to run a program again and again at the same time on a single machine: multiple windows were opened one on top of each other, and you could continue opening more and more windows of the same program. Sometimes, it would cause a crash for lack of computer resources.

Image 2

Today, in most cases, we want to make sure our program runs once per machine. For example, think of the same Excel document opened twice in the same computer, and two people work on each.

Obviously, unless we rename one document, how can we manage the changes in both instances of the same file? Therefore, MS Office allows you to run only one instance of a document at a time. Let us also say we own an accounting software which is run by people at the office. There is no reason to run it multiple times on the same machine. It is also a matter of a user-friendly design. If the user is not aware that the software is running and starts a new instance of it, it will not run and instead bring the focus to the one already running.

There is another aspect to this: sometimes, we need to make sure parts of our code will not access shared resources at the same time. Think of your code as if you were running a grid of railways: you do not want two trains running on the same track at the same time — we want them to be in sync, and for each train to run according to its unique schedule. Our program needs to run in sync of all its components and resources (though some programs run un-synchronically).

Now that you understand the problem, we can introduce one of the solutions: Mutex, which stands for Mutual Exclusion Object. The C++ Standard Library offers the std::mutex, which holds a mechanism used to protect shared resources from being simultaneously accessed by multiple threads or instances.

Mutex, which is a primitive type, offers exclusive, non-recursive ownership semantics:

A program, or a thread within a program, as well as a code block, which own a mutex, are safeguarded, so that other instances or threads will not be able to run the same program, thread, or code block — they will be locked and that will ensure running it once at any given time.

An attempt to gain ownership on that mutex while another resource has already locked it, will return a false value, so the calling party knows it is already locked. Going back to our example, if the mutex of our accounting software is locked, we will find the instance of the software that is already running and change the focus to it.

Think of mutex as if it was a voicemail — when someone calls your landline and starts recording a message in your voicemail, no one else can call and leave a message at the same time — the voicemail is locked. The moment a person finishes recording a message, another person can then call and leave a message. The “mutex” in this case is local to your voicemail. You can leave messages to other people, but your specific voicemail is locked during the time someone is in the process of recording a message. Of course, you can design a voicemail that will be able to record up to five or ten messages at once, but most voicemails will allow a single recording by design. This is the considerably basic idea of mutex — you don’t need to know more at this point.

Image 3

Semaphores — It All Started With Train Signals

Another way to control access to resources is using Semaphores, which help us synchronize our program. This method was invented by Edsger W. Dijkstra, a Dutch computer scientist, who originally designed semaphores as a method for train signaling back in 1965. A semaphore is a variable which is shared between threads and can be simplified as a data structure of a queue and a counter. The counter is initialized to a value which is either 0 or larger than 0. Using this structure. semaphores run two remarkably simple core operations:

wait — when a wait is acquired by the semaphore, other threads may still use it if the counter is not 0. So, if the initial value is ten, that means we allow ten threads to use this resource, and when each of them acquire the semaphore, the counter is decreased until reaching 0.

Signal or releaseOnce a thread is done using the resource, signal or release operations are used to release the semaphore, so in that case, the counter will increase.

If this is all too confusing, just think of semaphores as a guard at a convenient store back in the Covid-19 days: only few people were allowed to stay inside a closed premises at any given moment. There was a queue and then someone was allowed access. In semaphores, ‘wait’ means letting someone in, and decreasing the counter of the people that can be allowed in by one, if that counter is now 0, no one can go in. The moment someone leaves the store (“release”), the counter is promoted by one, so another person can go in. You can also compare it to a train signaling mechanism, which was its original design.

Image 4

You might ask yourself what the difference between mutex and semaphore is. The simple answer is that mutex uses a locking mechanism, while semaphore uses a signaling mechanism. Of course, there are other differences, and much more to learn about mutex and semaphore, and which I cannot cover in a single article.

History

  • 28th October, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Secured Globe, Inc.
United States United States
Author, key speaker, entrepreneur, cyber security, cyber forensics expert and consultant, as well as a hands on C++ professional with 25+ years of experience in the industry. Founded Secured Globe, Inc. together with her husband, Michael Haephrati. A professional painter, illustrator and photographer always seeking for the next great shot…

Comments and Discussions

 
GeneralMy vote is 4 Pin
Kai Binek23-Nov-22 6:05
Kai Binek23-Nov-22 6:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.