c 生产者与消费者
2013-10-30 14:20
363 查看
pthread_cond_timedwait 函数还有一个额外的参数可以设定等待超时,如果到达了abstime 所指 定的时刻仍然没有别的线程来唤醒当前线程,就返回ETIMEDOUT 。一个线程可以调 用pthread_cond_signal 唤醒在某个Condition Variable上等待的另一个线程,也可以调 用pthread_cond_broadcast唤醒在这个Condition Variable上等待的所有线程。 下面的程序演示了一个生产者-消费者的例子,生产者生产一个结构体串在链表的表头上,消费 者从表头取走结构体。
#include<stdio.h>
2 #include<stdlib.h>3 #include<pthread.h>4 #include<math.h>5 struct student{6 struct student *next;7 int data;8 };9 struct student *head;10 pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;11 pthread_cond_t cond=PTHREAD_COND_INITIALIZER;12 void *consumer(void *p){13 struct student *st;14 for(;;){15 pthread_mutex_lock(&lock);16 while(head==NULL){17 pthread_cond_wait(&cond,&lock);18 }19 st=head;20 head=st->next;21 pthread_mutex_unlock(&lock);22 printf("consume %d\n",st->data);23 free(st);24 sleep(1);25 }2627 }28 void *producer(void *p){29 struct student *st;30 for(;;){31 st=malloc(sizeof(struct student));32 st->data=rand()%1000+1;3334 printf("producer %d\n",st->data);35 pthread_mutex_lock(&lock);36 st->next=head;37 head=st;38 pthread_mutex_unlock(&lock);39 pthread_cond_signal(&cond);40 sleep(1);
} 43 } 44 45 int main(){ 46 pthread_t p1; 47 pthread_t p2; 48 pthread_create(&p1,NULL,producer,NULL); 49 pthread_create(&p2,NULL,consumer,NULL); 50 pthread_join(p1,NULL); 51 pthread_join(p2,NULL); 52 53 }
相关文章推荐
- 编译libtheora-1.1.1
- Linux/shell命令的实际应用——ldd查看可执行程序依赖的库文件
- C++STL介绍
- 数字转中文
- C# 钩子HOOK专题(1)
- Ext4之Store发送Ajax请求不带limit、page、start
- python 模块paramiko学习
- iOS7 SDK新特性
- error while loading shared libraries: xxx.so.x"错误的原因和解决办法
- C++异常处理(下)
- plsql 乱码 注册表 修改文件
- linux进程(一)概述和进程描述符
- select count(column_name) form table_name or select count(*) from table_Name
- widows相关命令
- 浮点数与0比较.
- C++异常处理例子(上)
- Springmvc 请求转发 No mapping found for HTTP request
- OCP-1Z0-052-V8.02-182题
- html中用IE条件判断
- 学习杂记