线程条件变量应用(消费者和生产着模型)
2013-11-05 21:16
369 查看
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> struct msg { struct msg *next; int num; }; struct msg *head = NULL; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp = NULL; for(;;) { pthread_mutex_lock(&lock); while(head == NULL) { pthread_cond_wait(&has_product,&lock); } mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("consumer %d\n",mp->num); free(mp); sleep(rand() % 5); } } void *producer(void *p) { struct msg *mp = NULL; for(;;) { mp = malloc(sizeof(*mp)); pthread_mutex_lock(&lock); mp->next = head; mp->num = rand()%1000; head = mp; printf("Produce %d\n",mp->num); pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(void) { pthread_t pid,cid; srand(time(NULL)); pthread_create(&pid,NULL,producer,NULL); pthread_create(&cid,NULL,consumer,NULL); pthread_join(pid,NULL); pthread_join(cid,NULL); return 0; }
相关文章推荐
- 13.11.5-对中间件的初步了解
- 指针
- 分治 Divide and Conquer 局部最小值 local optimal 棋盘问题
- uva 10912 - Simple Minded Hashing(计数)
- 让微积分变浮云吧
- SQL中如何使用patindex
- NAND flash的MTD分区与uboot中分区的理解
- SecureCRT跟centOs6.2中的Linux系统上传和下载文件(rz/sz)
- Linux 日历和计算器命令
- 极限的思想
- Html转UBB的JS版本【寻求更好的方案】
- [LeetCode]Median of Two Sorted Arrays
- 上古神器-AWK中高级实例分享-中
- 页面局部加载,适合Ajax Loading场景(Demo整理)
- xctool
- 《推荐系统实践》 阅读笔记
- SAM4E单片机之旅——5、LED呼吸和PWM
- Expression Blend实例中文教程(4) - 布局控件快速入门Canvas
- 页面局部加载,适合Ajax Loading场景(Demo整理)
- [Unity3d]U3d中基本GUI控件