[ACCEPTED]-How can you implement a condition variable using semaphores?-condition-variable

Accepted answer
Score: 10

Here's a paper from Microsoft Research [pdf] which deals with exactly 1 that.

Score: 0

One way of implementing X given semaphores 8 is to add a server process to the system, use 7 semaphores to communicate with it, and have 6 the process do all the hard work of implementing 5 X. As an academic exercise, this might be 4 cheating, but it does get the job done, and 3 it can be more robust to misbehaviour by 2 the client processes, or to their sudden 1 death.

Score: 0

I may be missing something here, but there 3 seem to be a simpler way to implement a 2 Condition from a Semaphore and Lock than 1 the way described in the paper.

class Condition {
    sem_t m_sem;
    int   m_waiters;
    int   m_signals;
    pthread_mutex_t *m_mutex;
public:

    Condition(pthread_mutex_t *_mutex){
        sem_init(&this->m_sem,0,0);
        this->m_waiters = 0;
        this->m_signals = 0;
        this->m_mutex = _mutex;
    }
    ~Condition(){}
    void wait();
    void signal();
    void broadcast();
};

void Condition::wait() {
    this->m_waiters++;
    pthread_mutex_unlock(this->m_mutex);
    sem_wait(&this->m_sem);
    pthread_mutex_lock(this->m_mutex);
    this->m_waiters--;
    this->m_signals--;
}

void Condition::signal() {
    pthread_mutex_lock(this->m_mutex);
    if (this->m_waiters && (this->m_waiters > this->m_signals)) {
        sem_post(&this->m_sem);
        this->m_signals++;
    }
    pthread_mutex_unlock(this->m_mutex);
}

More Related questions