Syncronizing Threads


Standard Buffer Example

/* It is the data that is shared so you only need one mutex. */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_w = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_r = PTHREAD_COND_INITIALIZER;
int buf_count = 0, buf_r_loc = 0, buf_w_loc = 0;
char buf[1024];

#define INC(x) (++x == 1024) ? (x) = 0 : (x)

char read_buf(void)
{
    char ret;

    pthread_mutex_lock(&mutex);
    while (buf_count == 0) {
        pthread_cond_broadcast(&cond_w);
        pthread_cond_wait(&cond_r, &mutex);
    }
    buf_count--;
    ret = buf[buf_r_loc];
    INC(buf_r_loc);
    pthread_cond_broadcast(&cond_w);
    pthread_mutex_unlock(&mutex);
    return(ret);
}

void write_buf(char ch)
{
    pthread_mutex_lock(&mutex);
    while (buf_count == 1024) {
	pthread_cond_broadcast(&cond_r);
	pthread_cond_wait(&cond_w, &mutex);
    }
    buf_count++;
    buf[buf_w_loc] = ch;
    INC(buf_w_loc);
    pthread_cond_broadcast(&cond_r);
    pthread_mutex_unlock(&mutex);
}


[TOP] [BACK] [FORWARD]


Prepared by Chris Provenzano (proven@mit.edu)