How to implement a condition variable using semaphores?

And back, I was thinking about how to implement different synchronization primitives in terms of each other. For example, in pthreads you get mutexes and condition variables, and semaphores can be built from them.

In the Windows API (or at least in older versions of the Windows API) there are mutexes and semaphores, but there are no variable conditions. I think it should be possible to build variable conditions from mutexes and semaphores, but for my life I just can't figure out how to do this.

Does anyone know of a good design for this?

+5
source share
4 answers
+8

- , , , , .

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);
}
+1

X , , X. , , .

0

All Articles