[webkit-dev] Change WTF::ThreadCondition::timedWait to use absolute time?

Dmitry Titov dimich at chromium.org
Tue Dec 30 18:21:22 PST 2008


For worker implementation of "run loop", I am looking to implement
MessageQueue::waitForMessageWithTimeout(), where timeout would be computed
from the the JS timer with nearest expiration. I am looking at using
WTF::ThreadCondition::timedWait for implementation but it seems it is not
implemented right... Before trying to send a patch, I'd like to ask here to
validate the idea.

It is defined with 'secondsToWait':


bool ThreadCondition::timedWait(Mutex& mutex, double secondsToWait)

while a corresponding pthread function takes absolute time:


int  pthread_cond_timedwait(pthread_cond_t *, pthread_mutex_t *, const
struct timespec *);

 The reason pthread function takes abs time is because pthread's function
can return 'spuriously'. I think the reason is that most implementation lack
the atomic "wake up and re-acquire the mutex" operation, so the conditions
can change between waking up and re-acquiring the mutex - and the wait can
return while in fact it should have not. Here is a piece of pthread doc (
https://computing.llnl.gov/tutorials/pthreads/man/pthread_cond_timedwait.txt
):

      When using condition variables there  is  always  a  Boolean
predicate  involving
       shared  variables  associated  with each condition wait that is
true if the thread
       should  proceed.   Spurious   wakeups   from   the
pthread_cond_timedwait()   or
       pthread_cond_wait() functions may occur. Since the return from
pthread_cond_timed-
       wait() or pthread_cond_wait() does not imply anything  about
the  value  of  this
       predicate, the predicate should be re-evaluated upon such return.

That means the waiting should always be done in a loop, checking if
the thread can actually proceed and if not, call wait function again,
like here:

    bool MessageQueue::waitForMessage()

    {

        MutexLocker lock(m_mutex);

        while (m_queue.isEmpty())

            m_condition.wait(m_mutex);

        .. consume message ...

    }

 In case of timed wait it means the absolute time should be computed
before such loop, and it explains why pthreads have timed wait
function with absolute time as a parameter. That means WTF timedWait
method should change prototype to take absolute time:

bool ThreadCondition::timedWait(Mutex& mutex, const struct timespec
*timeoutTime)

Then it's possible to implement blocking
MessageQueue::waitForMessageWithTimeout() to return exactly after
specified timeout or with a message.

Ok to change?

Dmitry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20081230/d83a99c5/attachment.html>


More information about the webkit-dev mailing list