- 1、本文档共13页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
操作系统实验报告何博伟
2013 年 4 月 27 日
实验内容
在 Windows 和 Linux 操作系统上,利用各自操作系统提供的 Mutex 和信号量机制(Win32 API
或 Pthreads),实现生产者/消费者问题。具体要求见”Operating System Concepts(Seventh
Edition)” Chapter 6 后的 Project(P236-241)。
实验目的
通过实验,理解 Win32 API、Pthreads 中 mutex locks、semaphores 等使用方法,并掌握如
何利用它们实现进程(线程)间的同步和互斥。
设计思路及流程图
? 初始化信号量值(full, empty, mutex)
? 利用系统调用,创建 Producer 和 Consumer 的线程若干
? Producer 线程执行函数:
? do { …
? 产生一个新的 product
? …
? wait(empty);
? wait(mutex);
? …
? 将新产生的 product 放入 buffer 中
? …
? signal(mutex);
? signal(full);
? } while (true);
? Consumer 线程执行函数:
? do {
? wait(full)
? wait(mutex);
? …
? 从 buffer 中移除一个 product
? …
? signal(mutex);
? signal(empty);
? …
? 对得到的 product 进行各种操作
? …
? } while (true);
? 结束程序
主程序流程图如下:
Start
Initialize
semaphores
Initialize
Producer
Consumer threads
Start threads
Wait for
termination…
Terminate the program.
Producer 程序流程图如下:
Start
Produce an item
Wait for semaphore:
empty
Wait for semaphore:
mutex
Insert the product into buffer
Signal semaphore:
mutex
Signal semaphore:
full
Consumer 程序流程图如下:
Start
Wait for semaphore:
full
Wait for semaphore:
mutex
Remove a product from buffer
Signal semaphore:
mutex
Signal semaphore:
empty
Consume the product
主要数据结构及其说明
本程序主要用到 bounded-buffer 来存储缓存的数据,为方便起见,缓冲区中的内容为 int 类
型。缓冲区主要结构如下图:
front
rear
环形缓冲区,拥有 front 和 rear 两个指针,以及 isEmpty 一个布尔变量。其中 front 表示缓冲
区的头部,rear 表示缓冲区尾部,isEmpty 表示缓冲区是否为空。
插入一个元素时,改变 isEmpty=true,如果尚未填满(front != rear)并且插入后移动 rear
指针指向下一个空槽。
删除元素时,先取出 front 指向的元素,然后将 front 往后移动一位,如果 front==rear,
则缓冲区空,置 isEmpty=true。
源程序及注释
#ifdef WIN32
#include Windows.h
#endif
#ifdef linux
#include pthread.h
#include semaphore.h
#endif
#include iostream
#include math.h
#include time.h
#include stdlib.h //调用rand()及srand()函数
using namespace std;
const int MAX_SEMAPHORE_VALUE = 5; //a.k.a MAX_BUFFER_SIZE
int buffer[MAX_SEMAPHORE_VALUE]; //buffer
int front=0, rear=0;
bool isFull = false;
const int WORKER_SIZE = 20;
inline void PrintLineL() {
cout endl
Enter to continue, Ctrl+C to quit. endl;;
}
in
文档评论(0)