读书人

Linux多线程编程简例六个

发布时间: 2012-09-12 09:21:30 作者: rapoo

Linux多线程编程简例6个

//sem, 生产者、消费者模型#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <semaphore.h>#defineNUM5sem_t blank_number, product_number;int queue[NUM];pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *consumer(void *p){int n = 0;for(;;){sem_wait(&product_number);printf("Consume -%d\n", queue[n]);queue[n] = 0;sem_post(&blank_number);n = (n + 1) % NUM;sleep(rand() % 5);}return NULL;}void *producer(void *arg){int n = 0;for(;;){sem_wait(&blank_number);queue[n] = rand() % 1000 + 1;printf("Produce +%d\n", queue[n]);sem_post(&product_number);n = (n + 1) % NUM;sleep(rand() % 5);}}int main(){pthread_t pid, cid;sem_init(&blank_number, 0, NUM);sem_init(&product_number, 0, 0);pthread_create(&pid, NULL, producer, NULL);pthread_create(&cid, NULL, consumer, NULL);pthread_join(pid, NULL);pthread_join(cid, NULL);sem_destroy(&blank_number);sem_destroy(&product_number);return 0;}



参考资料:http://www.eefocus.com/html/09-11/26160910394Yba.shtml


读书人网 >编程

热点推荐