生产者消费者问题-操作系统课程设计-英文_第1页
生产者消费者问题-操作系统课程设计-英文_第2页
生产者消费者问题-操作系统课程设计-英文_第3页
生产者消费者问题-操作系统课程设计-英文_第4页
生产者消费者问题-操作系统课程设计-英文_第5页
已阅读5页,还剩17页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Name of Project:Producer-Consumer ProblemCourse Name: Operating SystemCourse Number:CSCI 330Students Name:Students ID:Date of Submission: Dec 20, 2011Table of ContentsRequirement of Project.3Operating Environment.3Principle of Program.3Structure3Flow Chart4Code of the Program.5Results of Simulation.

2、8Considerable Improvement 9Conclusion.11References.12Requirement of ProjectThe producer-consumer problem illustrated as the model of bounded-buffer, require sequential processes or threads running asynchronously and possibly sharing data. There are several methods to solve this problem, and semaphor

3、e, mutex(simplified semaphore) and monitor are commonly used on this. This project requires us to make producers and consumers running as separated threads, and semaphores with full, empty, and mutex parameters to simulate this procedure.In the textbook, we are suggested to use Pthreads or Win32 API

4、, however, I decided to use Java to simulate the procedure, because Java is the most familiar language that we have learned.Because of the Java Virtual Machine (JVM) layer, many structures are made simple in Java compared to win32 API and C in UNIX environment, and we can simulate the problem withou

5、t a certain semaphore.Operating EnvironmentOS: Windows 7, JDK: Java 7 edition 1.7.0_02Principle of ProgramBecause of the limited Java programming skills, I can only simulate the procedure in the most simplified way. Only three sub-classes are put under the ProducerConsumer Class in the program, and

6、only one method which is the necessary main void method in this Class.The three sub-classes are storage, producer and consumer, and producer and consumer classes are set as Java threads, because they extend library class of Thread in java.lang.Object package.There are several objects and methods in

7、these three sub-classes, and they are carefully defined as private, public or synchronized. Structure:The full structure of whole program is illustrated in the table below.Super Class: ProducerConsumer With Object: p1p7 (seven producer objects), c1c3 (three consumer objects)With method: mainSub-clas

8、s: Godown / storage classInner variable: max_size, curnum / the number that the storage have currentlyInner method: produce(int), consume(int)Sub-class: ProducerInner variable: neednum / number of producingInner method: run / inherit from the Thread Class in java.lang.ObjectSub-class: ConsumerInner

9、variable: neednum / number of consumingInner method: run / inherit from the Thread Class in java.lang.ObjectFlow Chart:The flow chart of this program is illustrated as below:The key of realization of this procedure is that make each the producer and consumer a real java thread. By looking up the off

10、icial java doc in Oracle Websites, we can find details of the class Thread in java.lang.Object packages. I find some methods and examples of usage, and by the functions and methods provided by official, I use the method of notifyAll(), wait().Table of methods of java.lang.Object in official java doc

11、 is shown below:Method Summaryprotected HYPERLINK l o o class in java.lang Object HYPERLINK l l clone()Creates and returns a copy of this object.boolean HYPERLINK l l equals( HYPERLINK l o o class in java.lang Objectobj)Indicates whether some other object is equal to this tected void HYPERLINK l l f

12、inalize()Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. HYPERLINK l o o class in java.lang Class HYPERLINK l l getClass()Returns the runtime class of thisO HYPERLINK l l hashCode()Returns a hash code value for

13、 the object.void HYPERLINK l l notify()Wakes up a single thread that is waiting on this objects monitor.void HYPERLINK l l notifyAll()Wakes up all threads that are waiting on this objects monitor. HYPERLINK l o o class in java.lang String HYPERLINK l l toString()Returns a string representation of th

14、e object.void HYPERLINK l l wait()Causes the current thread to wait until another thread invokes the HYPERLINK l l notify()method or the HYPERLINK l l notifyAll()method for this object.void HYPERLINK l l wait(longtimeout)Causes the current thread to wait until either another thread invokes the HYPER

15、LINK l l notify()method or the HYPERLINK l l notifyAll()method for this object, or a specified amount of time has elapsed.void HYPERLINK l l wait(longtimeout, intnanos)Causes the current thread to wait until another thread invokes the HYPERLINK l l notify()method or the HYPERLINK l l notifyAll()meth

16、od for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.In this program, all the threads of producers and consumers are paralleled, and have same limits of authority. At the beginning, each thread starts individually, and order of sequence

17、 and the winner of competition is random.The successful running of any thread, all the threads would be waked up, and process would be restarted overly.As a result, each time has a different result of simulation.In some degree, this procedure simulates the practical situation.Code of the Program:Pac

18、kage project_of_os;importjava.lang.Object;publicclassProducerConsumerpublicstaticvoid main(String args) Godown godown = new Godown(30); /30为初始时库存值Consumer c1 = new Consumer(50, godown); Consumer c2 = new Consumer(20, godown);Consumer c3 = new Consumer(30, godown);Producer p1 = new Producer(10, godow

19、n);Producer p2 = new Producer(10, godown);Producer p3 = new Producer(10, godown);Producer p4 = new Producer(10, godown);Producer p5 = new Producer(10, godown);Producer p6 = new Producer(10, godown);Producer p7 = new Producer(80, godown);/各个线程并发运行,先后次序为随机,不能运行则休眠,每个线程结束后,会唤醒所有休眠的进程,重新并发运行c1.start();

20、c2.start();c3.start();p1.start();p2.start();p3.start();p4.start();p5.start();p6.start();p7.start();/* 仓库类*/class Godown publicstaticfinalintmax_size = 100; / 100为设置的最大库存量publicintcurnum; Godown() Godown(int curnum) this.curnum = curnum;/ 生产neednum数量的产品,无论是否生产都输出情况说明publicsynchronizedvoid produce(int

21、 neednum) / 测试是否能生产while (neednum + curnum max_size) System.out.println(要生产的产品数量 + neednum + 超过剩余库存量+ (max_size - curnum) + ,暂时不能执行生产任务!);try/ 当前的生产线程等待wait(); catch (InterruptedException e) e.printStackTrace();curnum += neednum;/ 满足生产条件,则进行生产System.out.println(已经生产了 + neednum + 个产品,现仓储量为 + curnum);

22、/ 唤醒在此对象monitor上等待的所有线程notifyAll();/消费neednum数量的产品,只有消费成功才输出状态,库存不足不显示信息,线程休眠publicsynchronizedvoid consume(int neednum) / 测试是否能消费while (curnum neednum)trywait();/ 当前的生产线程等待 catch (InterruptedException e) e.printStackTrace();/ 满足消费条件,则进行消费curnum -= neednum;System.out.println(已经消费了 + neednum + 个产品,现仓

23、储量为 + curnum);/ 唤醒在此对象monitor上等待的所有线程notifyAll();/* 生产者类,线程*/class Producer extends Thread privateintneednum; / 生产产品的数量private Godown godown; / 仓库Producer(int neednum, Godown godown) this.neednum = neednum;this.godown = godown;publicvoid run() duce(neednum); / 生产指定数量的产品/* 消费者类,线程*/class Consumer ext

24、ends Thread privateintneednum; / 生产产品的数量private Godown godown; Consumer(int neednum, Godown godown) this.neednum = neednum;this.godown = godown;publicvoid run() godown.consume(neednum); / 消费指定数量的产品Results of Simulation:The code, shown as below,“Godown godown = new Godown(30);Consumer c1 = new Consum

25、er(50, godown); Consumer c2 = new Consumer(20, godown);Consumer c3 = new Consumer(30, godown);Producer p1 = new Producer(10, godown);Producer p2 = new Producer(10, godown);Producer p3 = new Producer(10, godown);Producer p4 = new Producer(10, godown);Producer p5 = new Producer(10, godown);Producer p6

26、 = new Producer(10, godown);Producer p7 = new Producer(80, godown);”have the direct effects of the results. The first line set the initial number of the storage, and c1-c3, and p1-p7 set threads consume or produce the certain number of items. The max size of the storage is set to 100 in class Godown

27、.Therefore, several random results are shown in the figures below:Considerable Improvement - Using Semaphore in JavaIn all the material I have find, and several OS textbooks I read, it is believed that there is not a concrete semaphore in java program. However, when looking up the official java doc

28、in Oracle websites, I find a Semaphore Class provided in library of java.util.concurrent. The official declaration of this Class Semaphore is that:“Acountingsemaphore,conceptually, maintains a set of permits. Each HYPERLINK /javase/7/docs/api/java/util/concurrent/Semaphore.html#acquire() l acquire()

29、 acquire()blocks if necessary until a permit is available, and then takes it. Each HYPERLINK /javase/7/docs/api/java/util/concurrent/Semaphore.html#release() l release() release()adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; theSemaphorejust ke

30、eps a count of the number available and acts accordingly.Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kinds of synchronization control, the throughput advantages

31、 of non-fair ordering often outweigh fairness considerations.This class also provides convenience methods to HYPERLINK /javase/7/docs/api/java/util/concurrent/Semaphore.html#acquire(int) l acquire(int) acquireand HYPERLINK /javase/7/docs/api/java/util/concurrent/Semaphore.html#release(int) l release

32、(int) releasemultiple permits at a time. Beware of the increased risk of indefinite postponement when these methods are used without fairness set true.Memory consistency effects: Actions in a thread prior to calling a release method such asrelease() HYPERLINK /javase/7/docs/api/java/util/concurrent/

33、package-summary.html#MemoryVisibility l MemoryVisibility happen-beforeactions following a successful acquire method such asacquire()in another thread.”Moreover, there is a sample code for semaphore:import java.util.concurrent.*;publicclassSample_of_semaprivatestaticfinalintMAX_AVAILABLE = 100;privat

34、efinal Semaphore available = new Semaphore(MAX_AVAILABLE, true);public Object getItem() throws InterruptedException available.acquire();return getNextAvailableItem();publicvoid putItem(Object x) if (markAsUnused(x)available.release(); / Not a particularly efficient data structure; just for demopubli

35、cint items; /. whatever kinds of items being managedpublicboolean used= newbooleanMAX_AVAILABLE;protectedsynchronized Object getNextAvailableItem() for (int i = 0; i MAX_AVAILABLE; +i) if (!usedi) usedi = true;returnitemsi; returnnull; / not reached protectedsynchronizedboolean markAsUnused(Object item) for (int i = 0; i MAX_AVAILABLE; +i) if (item = itemsi) if (usedi) usedi = false;returntrue; elsereturnfalse; returnfalse; In the official documentation, we have many methods in this class, in order to acquire the status of the real semaphore

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论