[C++] MUTEX: Write Your First Concurrent Code

Learn to design concurrent code by implementing a thread-safe queue

Valentina Di Vincenzo
The Startup

--

In the last article, we understood what concurrency is and why synchronization is needed. Now, it’s time to explore different synchronization primitives offered by the C++ Standard Template Library.
The first one is std::mutex. First of all, here is a quick card about this article (this will come in handy if you start feeling lost between too many new concepts).

Now let’s start.

What is Mutex?

This is the basic structure of synchronization.
It models MUTual EXclusive access to shared data between multiple threads, by using a memory barrier (you can think of it as a door).

SYNTAX

  • Header | #include <mutex>
  • Declaration | std::mutex mutex_name;
  • To acquire the mutex | mutex_name.lock();
    The thread asks for unique ownership of the shared data protected by the mutex. It can successfully lock the mutex (and then no one else can access the same data) or…

--

--