recursive_mutex

recursive_mutexes differ from regular mutexes in that they allow recursive locking: a thread can lock a recursive mutex twice (or more times) without blocking itself. Other threads are still excluded.

recursive_mutexes are used when a thread will repeatedly enter sections of protected code as a result of recursion:

#include <mutex>
#include <thread>

::std::recursive_mutex
   mutex;

void function0(void)
{
   ::std::lock_guard
      <
      ::std::recursive_mutex
      >
      lock(mutex);            // Does not block
}

void function1(void)
{
   ::std::lock_guard
      <
      ::std::recursive_mutex
      >
      lock(mutex);
   
   function0();
}

int main(int argc, char ** argv)
{
   ::std::jthread( function1 );
   
   return 0;
}