Avatar of bachra04
bachra04
Flag for Canada asked on

pthread blocking queue

Hi ,


I want to create a pthread that is reading events from a blocking queue and execute them.

Any help on how to do that in pthread ?
C++C

Avatar of undefined
Last Comment
jkr

8/22/2022 - Mon
bachra04

ASKER
to clarify I have a list and I want to block on that list until it gets an element :

basically blocking pop_front in pthread.
ASKER CERTIFIED SOLUTION
jkr

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
bachra04

ASKER
Hi Jkr,

That's what i'm looking for. my only concern is that if pop_front is waiting undefinitely, does clear all stop that  or should I send a pthread_cond_signal(&m_event_cond)in that case ?
jkr

The problem with just signaling the condition variable is that you have nothing to return in that case. To avoid that, you could rewrite it as

    bool pop_front(T& ret) {  // will wait until there is an element to return

        pthread_mutex_lock(&m_queue_lock);
        if (m_queue.empty()) {
            pthread_cond_wait(&m_event_cond, &m_queue_lock);
        }

        if (m_queue.empty()) return false; // signalled without an addition to the container

        ret = m_queue.front();
        pthread_mutex_unlock(&m_queue_lock);

        return true;
    }

Open in new window


and evaluate to boolean return value to take that into account. And yes, you could as well set the condition variable in clear as well, depending on whether that is your desired functionality.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23