当前位置:首页 > 山东大学 计算机 2011 - 操作系统实验报告 - 最终版
//ring->Get(message) here. nempty->V();// ...
最后就是各信号量以及生产者/消费者线程的声明: void ProdCons() { int i;
DEBUG('t', \
nempty=new Semaphore(\声明empty信号量 nfull=new Semaphore(\ //声明full信号量 mutex=new Semaphore(\声明互斥信号量 // Put the code to construct all the semaphores here. // ....
ring=new Ring(BUFF_SIZE);// Put the code to construct a ring buffer object with size
//BUFF_SIZE here. // ... //*producers[N_PROD] = new Thread();
// create and fork N_PROD of producer threads
for (i=0; i < N_PROD; i++) {
// this statemet is to form a string to be used as the name for // produder i.
sprintf(prod_names[i], \
producers[i] = new Thread(prod_names[i]);//生产者线程初始化 // Put the code to create and fork a new producer thread using // the name in prod_names[i] and
// integer i as the argument of function \ // ...
producers[i]->Fork(Producer,i); //挂起生产者线程 };
// create and fork N_CONS of consumer threads for (i=0; i < N_CONS; i++) {
// this statemet is to form a string to be used as the name for // consumer i.
sprintf(cons_names[i], \
consumers[i] = new Thread(cons_names[i]);//消费者线程初始化 // Put the code to create and fork a new consumer thread using
// the name in cons_names[i] and
// integer i as the argument of function \ // ...
consumers[i]->Fork(Consumer,i); //挂起消费者线程 }; }
调试记录:
不管设置几个生产者,几个消费者,每次的输出结果基本一致。 实验结果:
最后执行完后输出得到tmp_0和tmp_1文件(由于这里消费者数量为2,所以有2个tmp文件) tmp_0:
producer id --> 0; Message number --> 0; producer id --> 1; Message number --> 0; producer id --> 0; Message number --> 2; producer id --> 2; Message number --> 1; tmp_1:
producer id --> 1; Message number --> 1; producer id --> 0; Message number --> 1; producer id --> 0; Message number --> 3; producer id --> 1; Message number --> 2;
producer id --> 2; Message number --> 0; producer id --> 2; Message number --> 2; producer id --> 2; Message number --> 3; producer id --> 1; Message number --> 3;
分析结果:
对于同一个消费者,相同的生产者,生产号是递增的,说明取的时候是按照顺序的。
结论分析与体会:
通过这个实验对生产者/消费者问题有了更深入的了解,之前只是一个生产者--一个消费者模式或者一个生产者--多个消费者模式,而多个生产者--多个消费者模式不仅仅需要考虑生产者/消费者之间的同步问题,同时生产者之间,消费者之间的互斥问题也同样需要考虑。
共分享92篇相关文档