cs24-22fa pthread_cond_signal

Introduction to Computing Systems (Fall 2022)

Name

pthread_cond_signal - signal a condition

Synopsis

#include <pthread.h>

int pthread_cond_signal(pthread_cond_t *cond);

Description

The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked. When each thread unblocked as a result of a pthread_cond_signal() returns from its call to pthread_cond_wait(), the thread shall own the mutex with which it called pthread_cond_wait(). The thread(s) that are unblocked shall contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

The pthread_cond_signal() function shall have no effect if there are no threads currently blocked on cond.

Example

#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>

bool done = false;
pthread_mutex_t mutex;
pthread_cond_t cond;

void *child(void *arg) {
    printf("child\n");

    // Must lock before updating condition, else get race condition
    pthread_mutex_lock(&mutex);
    done = 1;
    // Signal that at least one thread waiting on the condition
    // should wake up to check on the condition variable
    pthread_cond_signal(&cond);
    // Unlock since we are no longer setting the condition
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main(int argc, char *argv[]) {
    printf("parent: begin\n");

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    // Run a child thread that will eventually set done to 1
    pthread_t p;
    pthread_create(&p, NULL, child, NULL);

    // Must lock before checking condition, else get race condition
    pthread_mutex_lock(&mutex);
    while (!done) {
        // Upon call, pthread_cond_wait releases the mutex
        pthread_cond_wait(&cond, &mutex);
        // Upon return, pthread_cond_wait locks the mutex
        
        // Spurious wakeups may happen, so the condition
        // must be reevaluated upon return of pthread_cond_wait
    }
    printf("Wow! I'm done!\n");

    // Done confirming the condition done != 0, so unlock
    pthread_mutex_unlock(&mutex);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    printf("parent: end\n");
    return 0;
}

Return Value

If successful, the pthread_cond_signal() function shall return zero; otherwise, an error number shall be returned to indicate the error.

See Also

pthread_cond_init(), pthread_cond_destroy(), pthread_cond_wait()