std::recursive_mutex (C++)

The std::mutex is a non-recursive mutex and therefore can’t be locked again from the same thread before getting unlocked. This can lead quite fast to a deadlock. That’s the point where std::recursive_mutex comes in place. It can be locked multiple time from the same threat without the need to unlock it first.


Example – With deadlock

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

class Cache
{
public:
  Cache() : m_Mtx(), m_Val(0) {}

  bool update(int val) {
    std::lock_guard<std::mutex> lock(m_Mtx);

    bool updated = false;
    if (m_Val != val) {
      write(val);
      updated = true;
      std::cout << "val has been updated" << std::endl;
    }
    return updated;
  }

private:
  void write(int val) {
    std::lock_guard<std::mutex> lock(m_Mtx); // 2nd lock --> deadlock
    m_Val = val;
  }

  std::mutex m_Mtx;
  int m_Val;
};

int main()
{
  Cache cache;
  std::thread t(&Cache::update, &cache, 42);
  t.join();

  return 0;
}