Home Patches

Timed Lock for Mutex Class

kalaxykalaxy Member Kalon MillsOrganization: Omniture, Inc.Project: Distributed/Parallel processing.
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

  • michimichi Member Michi HenningOrganization: Triodia TechnologiesProject: I have a passing interest in Ice :-) ✭✭✭
    Have you checked out timed locks in the manual?

    Cheers,

    Michi.
  • kalaxykalaxy Member Kalon MillsOrganization: Omniture, Inc.Project: Distributed/Parallel processing.
    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.
  • michimichi Member Michi HenningOrganization: Triodia TechnologiesProject: I have a passing interest in Ice :-) ✭✭✭
    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.
  • kalaxykalaxy Member Kalon MillsOrganization: Omniture, Inc.Project: Distributed/Parallel processing.
    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.
  • bernardbernard Jupiter, FLAdministrators, ZeroC Staff Bernard NormierOrganization: ZeroC, Inc.Project: Ice ZeroC Staff
    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
Sign In or Register to comment.