易截截图软件、单文件、免安装、纯绿色、仅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编程(三) HCI层编程

1. HCI层协议概述:
HCI提供一套统一的方法来访问Bluetooth底层。如图所示:
从图上可以看出,Host Controller Interface(HCI)  就是用来沟通Host和Module。Host通常就是PC, Module则是以各种物理连接形式(USB,serial,pc-card等)连接到PC上的bluetooth Dongle。
在Host这一端:application,SDP,L2cap等协议 ......

实战Linux Bluetooth编程(六) L2CAP编程实例

例一:发送Signaling Packet:
Signaling Command是2个Bluetooth实体之间的L2CAP层命令传输。所以得Signaling Command使用CID 0x0001.
多个Command可以在一个C-frame(control frame)中发送。
 如果要直接发送Signaling Command.需要建立SOCK_RAW类型的L2CAP连接Socket。这样才有机会自己填充Command Code,Identi ......

C、C++和C#的不同之处

C是面向过程的程序设计,程序=数据结构+算法 [最原始,但编个程确实不易]
C++是面向对象的程序设计,程序=多个类+消息(类=数据结+算法)[比较容易上手]
C# 是纯面向对象的语言[更加比较容易上手]
VC/VC++/VC# 只是用来开发C/C++/C#应用程序的软件中的一种。
......

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号