Link to home
Start Free TrialLog in
Avatar of bachra04
bachra04Flag 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 ?
Avatar of bachra04
bachra04
Flag of Canada image

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
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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 ?
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.