/* 测试:生产者线程将1 到10000 的整数送入缓冲区,消费者线 程从缓冲区中获取整数,两者都打印信息*/ #define OVER ( - 1) struct prodcons buffer; void *producer(void *data) { int n; for (n = 0; n < 10000; n++) { printf("%d --->\n", n); put(&buffer, n); } put(&buffer, OVER); return NULL; }
void *consumer(void *data) { int d; while (1) { d = get(&buffer); if (d == OVER) break; printf("--->%d \n", d); } return NULL; }
int main(void) { pthread_t th_a, th_b; void *retval; init(&buffer); /* 创建生产者和消费者线程*/ pthread_create(&th_a, NULL, producer, 0); pthread_create(&th_b, NULL, consumer, 0); /* 等待两个线程结束*/ pthread_join(th_a, &retval); pthread_join(th_b, &retval); return 0; }
|