/* Standard Buffer Example */

char buf[1024];\cr
int buf_count = 0, buf_r_loc = 0, buf_w_loc = 0;
pthread_cond_t cond_r = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_w = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

/*	Only need one mutex, because there is only one set of data. */

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

char read_buf(void)
{
	char ret;\cr

	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(but_w_loc);
	pthread_cond_broadcast(&cond_r);
	pthread_mutex_unlock(&mutex);
}


