timed_mutex

timed_mutexes differ from regular mutexes in that they provide timed locking functions.

timed_mutex. try_lock_for tries to lock a mutex until a specified duration has elapsed. timed_mutex. try_lock_until tries to lock the mutex until a specific time point. Both functions return false if, after the duration has elapsed, locking was unsuccessful. Note that both of these functions may block for longer than the specified timeout duration due to scheduling or resource contention delays.

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

::std::timed_mutex
   mutex;

void function(unsigned thread_index)
{
   auto const
      time_now = ::std::chrono::steady_clock::now();
   
   if (
         mutex.try_lock_until
            (
            time_now + ::std::chrono::seconds(1)
            )
      )
   {
      ::std::this_thread::sleep_for
         (
         ::std::chrono::seconds(2)
         )
         ;
      
      mutex.unlock();
   }
   else
   {
      ::std::cout << "Thread "
                  << thread_index
                  << " was excluded"
                  << ::std::endl
                     ;
   }
}

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