One message

2005.3.26:about 8 clock. Hou give me a message sended by mobile phone

"宝贝,不要让我白等,明白吗?"

I will remember this forever.

I must do my best to prove that It's desire to wait me.

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #define SIZE 10 int in=0; int out=0; int buffer[SIZE]; sem_t empty; sem_t full; pthread_mutex_t mutex; void *Producer() { int nextp=0; int i=0; for(; i <10; ++i) { int time = rand() % 10 + 1; usleep(time*100000); sem_wait(&empty); pthread_mutex_lock(&mutex); nextp = nextp + 1; buffer[in] = nextp; printf("Produce one message:%d\n", nextp); fflush(stdout);//printf后请一定调用这句刷新输出缓存 in = (in + 1) % SIZE; pthread_mutex_unlock(&mutex); //互斥锁解锁 sem_post(&full); } } void *Consumer() { //请补充消费者线程函数代码 int i=0; for(i=0;i<10;++i) { int time=rand()%10+1; usleep(time*100000); sem_wait(&full); pthread_mutex_lock(&mutex); int nextc=buffer[out]; out=(out+1)%SIZE; printf("Consume one message:%d\n",nextc); fflush(stdout); pthread_mutex_unlock(&mutex); sem_post(&empty); } } int main() { sem_init(&empty, 0, 10); //信号量初始化(最多容纳10条消息,容纳了10条生产者将不会生产消息) sem_init(&full, 0, 0); pthread_mutex_init(&mutex, NULL); //互斥锁初始化 pthread_t producid; pthread_t consumid; pthread_create(&producid, NULL, Producer, NULL); //创建生产者线程 pthread_create(&consumid, NULL, Consumer, NULL); //创建消费者线程 pthread_join(producid, NULL); pthread_join(consumid, NULL); sem_destroy(&empty); //信号量的销毁 sem_destroy(&full); pthread_mutex_destroy(&mutex); //互斥锁的销毁 return 0; }
06-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值