首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Linux多线程编程简例六个

2012-09-12 
Linux多线程编程简例6个//sem, 生产者、消费者模型#include stdlib.h#include pthread.h#include stdi

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


热点排行