Pthread event that wakes up only pending threads

In my C ++ program, I have a CEvent class with trigger and wait functions based on pthreads (works on Linux). The implementation is pretty obvious (i.e. many examples on the Internet) if there is one waiting process. However, now I need to fulfill the requirement that several threads are expected for the event, and ALL SHOULD wake up with reliability when calling trigger (). As a second condition, only those threads should appear that were waiting when trigger () was called.

My current code is:

void CEvent::trigger() {
    pthread_mutex_lock(&mutex);
    wakeUp = true;
    pthread_cond_broadcast(&condition)
    pthread_mutex_unlock(&mutex);
    wakeUp = false;
}

void CEvent::wait() {
    pthread_mutex_lock(&mutex);
    while (!wakeUp)
        pthread_cond_wait(&condition, &mutex)

    pthread_mutex_unlock(&mutex);
}

, , , wakeUp false. reset wakeUp ( ) , wait(), , . wakeUp = false mutext .

: * pthread_cond_broadcast? , , ? * ?

+3
1

, . , (, , ), , wakeUp. , ( ) , wakeUp . , wakeUp reset .

- - , , . , , .

// wake up "waiters" count of waiting threads
void CEvent::trigger()
{
    pthread_mutex_lock(&mutex);

    // wakey wakey
    wakeUp = true;
    pthread_cond_broadcast(&condition);

    // wait for them to awake
    while (waiters>0)
      pthread_cond_wait(&condition, &mutex);

    // stop waking threads up
    wakeUp = false;

    // let any "other" threads which were ready to start waiting, do so
    pthread_cond_broadcast(&condition);
    pthread_mutex_unlock(&mutex);
}

// wait for the condition to be notified for us
void CEvent::wait()
{
    pthread_mutex_lock(&mutex);

    // wait for us to be allowed to start waiting
    // we have to wait until any currrently being woken threads have gone
    while (wakeUp)
        pthread_cond_wait(&condition, &mutex);

    // our turn to start waiting
    waiters ++;

    // waiting
    while (!wakeUp)
        pthread_cond_wait(&condition, &mutex);

    // finished waiting, we were triggered
    waiters --;

    // let the trigger thread know we're done
    pthread_cond_broadcast(&condition);
    pthread_mutex_unlock(&mutex);
}
+3
source

Source: https://habr.com/ru/post/1709281/


All Articles