易截截图软件、单文件、免安装、纯绿色、仅160KB

生产者 消费者问题实现 (linux下C语言)

操作系统的一个经典问题是"生产者-消费者"问题, 这涉及同步信号量和互斥信号量的应用, 在这里,我用线程的同步和互斥来实现.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 2   // 消费者或者生产者的数目
#define M 10 // 缓冲数目
int in = 0;   // 生产者放置产品的位置
int out = 0; // 消费者取产品的位置
int buff[M] = {0}; // 缓冲初始化为0, 开始时没有产品
sem_t empty_sem; // 同步信号量, 当满了时阻止生产者放产品
sem_t full_sem;   // 同步信号量, 当没产品时阻止消费者消费
pthread_mutex_t mutex; // 互斥信号量, 一次只有一个线程访问缓冲
int product_id = 0;   //生产者id
int prochase_id = 0; //消费者id
/* 打印缓冲情况 */
void print()
{
int i;
for(i = 0; i < M; i++)
   printf("%d ", buff[i]);
printf("\n");
}
/* 生产者方法 */

void *product()
{
int id = ++product_id;
while(1)
{
   // 用sleep的数量可以调节生产和消费的速度,便于观察
   sleep(1);
   //sleep(1);
  
   sem_wait(&empty_sem);
   pthread_mutex_lock(&mutex);
  
   in = in % M;
   printf("product%d in %d. like: \t", id, in);
  
   buff[in] = 1;  
   print();  
   ++in;
  
   pthread_mutex_unlock(&mutex);
   sem_post(&full_sem);  
}
}
/* 消费者方法 */
void *prochase()
{
int id = ++prochase_id;
while(1)
{
   // 用sleep的数量可以调节生产和消费的速度,便于观察
   sleep(1);
//sleep(1);
  
   sem_wait(&full_sem);
   pthread_mutex_lock(&mutex);
  
   out = out % M;
   printf("prochase%d in %d. like: \t", id, out);
  
   buff[out] = 0;
  


相关文档:

实战Linux Bluetooth编程 (七) SDP协议

Service Discovery Protocol(SDP)提供一种能力,让应用程序有方法发现哪种服务可用以及这种服务的特性。
服务发现协议(SDP或Bluetooth SDP)在蓝牙协议栈中对蓝牙环境中的应用程序有特殊的含意,发现哪个服务是可用的和确定这些可用服务的特征。SDP定义了bluetooth client发现可用bluetooth server服务和它们的特征的方法。 ......

如何选择最适合的Linux版本

 作者:51cto
http://www.ccw.com.cn 2009-02-27 11:06:03
当你对别人说,“我要买辆车。”他马上就会问你:“什么车?”福特、丰田、还是本田?是双门跑车、小轿车、还是面包车?当然,还有其他类似的问题。
同样,如果你说“我想安装Linux!”你会被问到同样的问题:哪个Linu ......

Linux Assembly "Hello World" Tutorial, CS 200

 
by Bjorn Chambless
Introduction
The following is designed familiarize the reader with programming in x86 (AT&T
style, that produced by gcc) assembly under Linux and how to interface assembly
and higher-level language code (i.e. C). The tutorial will also briefly cover
debugging yo ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号