The Risks of Mutexes

Contents[Show]

The usage of mutexes seems extremely simple. There is a critical section in the code that a single thread can only access at any point in time. It's ensured by a mutex m. The calls m.lock() and m.unlock() guarantee this exclusivity. But the devil is in the details.

Deadlock

The different names for deadlocks are frightening. Some call them deadly embrace  (hug of death :-)? or kiss of death. But wait, what is a deadlock?

Deadlock
   A deadlock is a state in which at least two threads are blocked because each thread is waiting for the release of some resource with which the other thread works before it releases its resource.

The result of a deadlock is a total standstill. The Thread and usually the whole program is blocked forever. It is easy to produce a deadlock. Curious?

Exceptions and unknown code

std::mutex m;
m.lock();
sharedVariable= getVar();
m.unlock();

 

If the unknown code in the function getVar() throws an exception, m.unlock() will not be called. Every attempt to ask for the mutex m will fail, and the program will block. Forever. But that is not the only issue with that piece of code. It calls some (unknown to us) function get.Var(), while m.lock() is active. What will happen if the function getVar() tries to get the same lock? Of course, you know it—a deadlock.

Do you want to have a more visual example?

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

Lock mutexes in a different order

Deadlock

 

Thread 1 and 2 need access to two resources to finish their work. Unfortunately, they ask for the resources protected by two mutexes in a different order. In this case, the thread executions will interleave so that thread 1 gets mutex 1, then thread 2 gets mutex 2, and we have a standstill. Each thread wants to get the other's mutex. For this, the thread has to wait for the release of the resource.

 

It's easy to express the picture in code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// deadlock.cpp

#include <iostream>
#include <chrono>
#include <mutex>
#include <thread>

struct CriticalData{
  std::mutex mut;
};

void deadLock(CriticalData& a, CriticalData& b){

  a.mut.lock();
  std::cout << "get the first mutex" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1));
  b.mut.lock();
  std::cout << "get the second mutex" << std::endl;
  // do something with a and b
  a.mut.unlock();
  b.mut.unlock();
  
}

int main(){

  CriticalData c1;
  CriticalData c2;

  std::thread t1([&]{deadLock(c1,c2);});
  std::thread t2([&]{deadLock(c2,c1);});

  t1.join();
  t2.join();

}

 

Thread t1 and thread t2 call the function deadlock (lines 12 - 20). To process deadlock, both functions need the  CriticalData c1 and c2 (lines 27 and 28). Because the objects c1 and c2 must be protected from shared access, they  have a mutex (to keep this example code short and straightforward CriticalData doesn't have any other methods or members apart from mutex)

Only a sleep about 1 Millisecond in line 16, and we have the deadlock.
 

deadlockCode

The only choice now is the press CTRL+C to kill the process.

What's next?

Honestly, the example will not boost your confidence in writing multithreading programs. Additionally, the complexity will increase to the power of 2, which each new mutex. The solution to the problem is locks because they safely encapsulate mutexes. How? Have a look here. (Proofreader Alexey Elymanov)

 

 

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Tags: mutex

Comments   

0 #1 Jeannine 2017-01-31 05:22
I have learn a few just right sttuff here. Certainly value bookmarking for revisiting.
I wonder how much attempt you put to make such a magnificent informative site.
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 4333

Yesterday 4550

Week 4333

Month 26007

All 12104216

Currently are 205 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments