jeudi 25 mai 2017

std::timed_mutex::try_lock_for fails immediately

I'm using a std::timed_mutex for the first time and it's not behaving the way I expect. It appears to fail immediately instead of waiting for the mutex. I'm providing the lock timeout in milliseconds (as shown here http://ift.tt/2rmBPlA). But the call to try_lock_for() fails right away.

Here's the class that handles locking and unlocking the mutex:

  const unsigned int DEFAULT_MUTEX_WAIT_TIME_MS = 5 * 60 * 1000;

  class ScopedTimedMutexLock
  {
  public:
     ScopedTimedMutexLock(std::timed_mutex* sourceMutex, unsigned int numWaitMilliseconds=DEFAULT_MUTEX_WAIT_TIME_MS)
        m_mutex(sourceMutex)
     {
        if( !m_mutex->try_lock_for( std::chrono::milliseconds(numWaitMilliseconds) ) )
        {
           std::string message = "Timeout attempting to acquire mutex lock for ";
           message += Conversion::toString(numWaitMilliseconds);
           message += "ms";
           throw MutexException(message);
        }
     }
     ~ScopedTimedMutexLock()
     {
        m_mutex->unlock();
     }
  private:
     std::timed_mutex* m_mutex;
  };

And this is where it's being used:

  void  CommandService::Process( RequestType& request )
  {
     unsigned long callTime =
        std::chrono::duration_cast< std::chrono::milliseconds >(
           std::chrono::system_clock::now().time_since_epoch()
        ).count();

     try
     {
        ScopedTimedMutexLock lock( m_classMutex, request.getLockWaitTimeMs(DEFAULT_MUTEX_WAIT_TIME_MS) );
        // ... command processing code goes here
     }
     catch( MutexException& mutexException )
     {
        unsigned long catchTime =
           std::chrono::duration_cast< std::chrono::milliseconds >(
              std::chrono::system_clock::now().time_since_epoch()
           ).count();
        cout << "The following error occured while attempting to process command"
             << "\n   call  time: " << callTime
             << "\n   catch time: " << catchTime;
        cout << mutexException.description();
     }
  }

Here's the console output:

The following error occured while attempting to process command
   call  time: 1131268914
   catch time: 1131268914
Timeout attempting to acquire mutex lock for 300000ms

Any idea where this is going wrong? Is the conversion to std::chrono::milliseconds correct? How do I make try_lock_for() wait for the lock?

Aucun commentaire:

Enregistrer un commentaire