生产者 消费者问题实现 (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;
 
相关文档:
1. HCI层协议概述:
HCI提供一套统一的方法来访问Bluetooth底层。如图所示:
从图上可以看出,Host Controller Interface(HCI) 就是用来沟通Host和Module。Host通常就是PC, Module则是以各种物理连接形式(USB,serial,pc-card等)连接到PC上的bluetooth Dongle。
在Host这一端:application,SDP,L2cap等协议 ......
//输入一个数组,再修改这个数组所有元素,如何实现?
int main()
{
vector<int> a;
int i(0);
while(cin>>i)
a.push_back(i);
//////////////////////////////////////////////////////输出建立的数组:
cout << "得到的数组为:" << ......
1.已知strcpy 函数的原型是:
char *strcpy(char *strDest, const char *strSrc);
其中strDest 是目的字符串,strSrc 是源字符串。不调用C++/C 的字符串库函数,请编写函数 strcpy
答案:
char *strcpy(char *strDest, const char *strSrc)
{
if ( strDest == NULL || strSrc == NULL)
return NULL ;
if ( strDest ......
<!--
@page { margin: 2cm }
P { margin-bottom: 0.21cm }
-->
在本文中,
Linux
是指草根版的
Linux
,也就是说,
Linux
是正宗的
GNU/Linux
。现在的问题是,在中国,为什么
GNU/Linux
要远离硬盘?这是什么原因造成的?
......
#include <iostream>
#include <pwd.h>
#include <sys/types.h>
#include <stddef.h>
#include <string>
#include <list>
using namespace std;
void GetUser(list<string>& lsUser);
int main()
{
list<string> lsUser;
GetUser(lsUser);
cout <&l ......