Skip to main content
Engineering LibreTexts

10.5: Condition variable implementation

  • Page ID
    40638
  • The Cond structure I used in the previous section is a wrapper for a type called pthread_cond_t, which is defined in the POSIX threads API. It is very similar to Mutex, which is a wrapper for pthread_mutex_t. Both wrappers are defined in utils.c and utils.h.

    Here’s the typedef:

    typedef pthread_cond_t Cond;
    

    make_cond allocates space, initializes the condition variable, and returns a pointer:

    Cond *make_cond() {
        Cond *cond = check_malloc(sizeof(Cond)); 
        int n = pthread_cond_init(cond, NULL);
        if (n != 0) perror_exit("make_cond failed");
     
        return cond;
    }
    

    And here are the wrappers for cond_wait and cond_signal.

    void cond_wait(Cond *cond, Mutex *mutex) {
        int n = pthread_cond_wait(cond, mutex);
        if (n != 0) perror_exit("cond_wait failed");
    }
    
    void cond_signal(Cond *cond) {
        int n = pthread_cond_signal(cond);
        if (n != 0) perror_exit("cond_signal failed");
    }
    

    At this point there should be nothing too surprising there.

    • Was this article helpful?