Archived

This forum has been archived. Please start a new discussion on GitHub.

Timed Lock for Mutex Class

It would be really great if you could add a timedLock function to the Mutex class. Below is an idea of how it might work for the pthread world.
inline bool
Mutex::timedLock(const Time& timeout) const
{
    timeval tv = Time::now() + timeout;
    timespec ts;
    ts.tv_sec = tv.tv_sec;
    ts.tv_nsec = tv.tv_usec * 1000;
    int rc = pthread_mutex_timedlock(&_mutex, &ts);

    if (rc != 0 && rc != ETIMEDOUT)
    {
        if(rc == EDEADLK)
        {
            throw ThreadLockedException(__FILE__, __LINE__);
        }
        else
        {
            throw ThreadSyscallException(__FILE__, __LINE__, rc);
        }
    }
    return (rc == 0);
}

I don't know much about the Windows world. Maybe it's overly complex and that's why you haven't already done it.

Comments

  • Have you checked out timed locks in the manual?

    Cheers,

    Michi.
  • michi wrote: »
    Have you checked out timed locks in the manual?

    Yes and thanks for pointing it out, but it looks like it is only used for the RWRecMutex. I'll probably end up using the RWRecMutex but I don't need the RW or Rec functionality, which according to your Efficiency Considerations page it has [potentially significant] overhead in size and time.
  • Yes, RWRecMutex has more overhead than a plain mutex. But I suggest that you benchmark your code before rejecting RWRecMutex: unless the critical region you are protecting is very small, and unless you are locking and unlocking that region very frequently, chances are that you will not notice any difference.

    Cheers,

    Michi.
  • michi wrote: »
    ... chances are that you will not notice any difference.

    Good point. You are probably right that in my case that I won't notice a thing. I guess I was just looking for a theoretically most efficient solution without realizing the practical details.
  • bernard
    bernard Jupiter, FL
    kalaxy wrote: »
    I don't know much about the Windows world. Maybe it's overly complex and that's why you haven't already done it.

    On Windows, the underlying primitive is a CRITICAL_SECTION, and there is no associated timed-wait function. That's why it's not practical to add timedLock to IceUtil::Mutex.

    Cheers,
    Bernard