On 7/2/07, Anthony Williams <anthony_w.geo@yahoo.com> wrote:
rick68 <rick68@gmail.com> writes:

> I try timed_mutex whit linux, but it not work.

> void timed_mutex::do_lock()
> {
>    int res = 0;
>    res = pthread_mutex_lock(&m_mutex);
>    assert(res == 0);
>
>    while (m_locked)
>    {
>        res = pthread_cond_wait(&m_condition, &m_mutex);
>        assert(res == 0);
>    }
>
>    assert(!m_locked);
>    m_locked = true;
>
>    res = pthread_mutex_unlock(&m_mutex);
>    assert(res == 0);
> }
> All while-loop never running, because of
> boost::timed_mutex::scoped_timed_lock will check m_locked is false.

Yes. The loops are there so that if the mutex is already locked (m_locked is
true), do_lock will wait for the lock to become available. If the mutex is
unlocked (m_locked is false) then do_lock doesn't have to wait, so doesn't run
the while loop.

If I use boost::timed_mutex::scoped_timed_lock to do lock (m_locked is true)

==<boost/thread/detail/lock.hpp>==
void boost::detail::thread::scoped_try_lock<boost::timed_mutex>::lock()
{
        if (m_locked) throw lock_error();
        lock_ops<TimedMutex>::lock(m_mutex);
        m_locked = true;
}
========================

lock will throw lock_error, so I thought maybe to use while-loop will be fine.


> So, I change while-loop to do-while-loop:
>
> ============================================
> void timed_mutex::do_lock()
> {
>    int res = 0;
>    res = pthread_mutex_lock(&m_mutex);
>    assert(res == 0);
>
>    do
>    {
>        res = pthread_cond_wait(&m_condition, &m_mutex);
>        assert(res == 0);
>    } while (res);
>
>    assert(!m_locked);
>    m_locked = true;
>
>    res = pthread_mutex_unlock(&m_mutex);
>    assert(res == 0);
> }

This will deadlock! If there is no other thread holding the mutex (m_locked is
false) then this will enter the condition wait, but no thread will notify the
condition: deadlock.

 Oh, you are right! :p
But I don't have any idea let timed_mutex to wait... :(


> It's work very well~ :)

What exactly are you trying to achieve? If you let us know what you want to do
(in your code), then someone might be able to propose a way of achieving that
without breaking timed_mutex.

I just read about thread code and test it.

Can use condition and mutex to substitute for timed_mutex, but I want to know how to use timed_mutex.


Good Lucky~

rick