Are you developing a multi-threaded tool?

Sooner or later, you will likely need to use a Semaphore.

What Is aSemaphore?

Terminal window showing the manual page for the Mutt email client on Linux

You have likely used semaphores many times in your life without specifically realizing you were doing so!

That handle is the semaphore variable protecting either the waterway or the road from accidents.

Thus, the waterway and roads could be seen as other variables protected by the semaphore.

Article image

The semaphore variable can control access to another set of variables.

For example, the up state of the handle prevents the

and

variables from being updated, etc.

While the scenario described here is not only a semaphore, but it is also a simple mutex.

Command line example of bridge status update and output

Mutex stands for “mutually exclusive.”

Now that we have a better understanding of semaphores let’s implement one in Bash.

Implementing a Semaphore in Bash: Easy, or Not?

A semaphore implementation in Bash

“; else echo “Ships may pass!

“; fi

BRIDGE=down

In this code, the variableBRIDGEholds our bridge status.

When we set it toup, ships may pass and when we set it todown, cars may pass.

The shared/common resource, in this case, is our bridge.

However, this example is single-threaded, and thus we never ran into a semaphore requiredsituation.

Finally, as soon as we introduce multiple threads which can affect theBRIDGEvariable we run into issues.

Even a well-written program that employs semaphores is not guaranteed to be fully thread-safe.

In other words, there are multiple threads or tasks which all run at the same time.

Waiting 2 minutes before re-check.”

Firstly, let’s assume another operator has recently moved the bridge up within the last minute.

As such, there is another thread executing code in a function similar to this one calledraise_bridge.

it’s possible for you to also see this mandatory 5-minute wait implemented in this function assleep 300.

Can you spot any?

The"Lower bridge command accepted, locking semaphore and lowering bridge"is not thread-safe!

Directly after each other on the screen!

More scary still is the fact that both threads can proceed toBRIDGE_SEMAPHORE=1, and both threads can continue executing!

While this code implements a semaphore, it is thus by no means thread-safe.

As stated, multi-threaded coding is complex and requires much expertise.

However, the fact it is possible is what makes it dangerous.

Creating thread-safe code in Bash is not an easy feat.

Wrapping up

In this article, we have a look at what a semaphore is.

We also briefly touched on the subject of a mutex.

We also explored how complex implementing a reliable semaphore-based solution is.