samedi 16 juillet 2022

Can unique mutex cause delay?

I wonder if the mutex of function "setEvent" can cause a delay in the following situations.


void CTest::threadFucn_run()
{
    while(true)
    {
        ... // tcp connect if client disconnected .. etc. (if connected, skip

        bool prev_event = m_bEvent;

        std::unique_lock<std::mutex> lock(m_mutex_event);        // "A"
        m_cv_event.wait_for(lock, std::chrono::seconds(10),
                [&] { return (m_bEvent != prev_event); }

        // proc (send message m_bEvent state or alive signal to server)
        ...
    }
}

void CTest::setEvent(bool _on)    // called from other class
{
    std::unique_lock<std::mutex> lock(m_mutex_event);        // "B"
    m_bEvent = _on;

    m_cv_event.notify_one();
}

The "m_" keyword is all member variables.

In normal cases, it is expected that "B" will lock, send an event message after m_bEvent changes, or send an alive status over period of 10 seconds.

However, in the worst case, if "A" is locked, can the "setEvent" function wait for up to less than 10 seconds? (Because of "B")

Even if the send event message is sent a little late, the setEvent should be returned as soon as possible.

I am currently checking the m_bEvent status by repeating the while statement(Sleep 10ms), but considering the CPU usage, I am considering introducing condition variable.

Aucun commentaire:

Enregistrer un commentaire