东华大学操作系统读者写者实验报告
读者写者实验报告

读者写者实验报告
读者写者问题是指一个共享固定大小缓冲区的进程间通信问题,其中固定大小的缓冲区被多个读者进程和写者进程所共享。
读者进程从缓冲区中读取数据,而写者进程将数据写入缓冲区。
本实验目的是通过使用互斥锁、条件变量和信号量等同步机制,构建一个读者写者问题的解决方案。
实验环境:
- 操作系统:Linux
-编程语言:C语言
实验步骤:
1.创建共享内存缓冲区,用于读者和写者的数据传递。
2.创建互斥锁,用于保护共享内存缓冲区的访问。
3.创建条件变量,用于读者和写者之间的协调。
4.创建读者进程和写者进程,模拟读者写者的并发操作。
5.在读者进程中,通过互斥锁保护共享内存缓冲区,读取数据,并更新计数器。
6.在写者进程中,通过互斥锁保护共享内存缓冲区,写入数据,并更新计数器。
7.使用条件变量实现读者优先或写者优先的策略。
实验结果:
通过实验,我成功实现了读者写者问题的解决方案。
使用互斥锁可以保护共享资源的访问,防止读者和写者同时访问。
使用条件变量可以实现读者优先或写者优先的策略。
实验总结:
通过本次实验,我深入了解了读者写者问题,并且掌握了使用互斥锁、条件变量和信号量等同步机制来解决读者写者问题的方法。
在实现过程中,我遇到了一些困难,例如死锁和竞争条件等问题。
通
过调试和改进代码,我成功解决了这些问题,提高了程序的稳定性和性能。
在以后的工作中,我会更加注重并发编程的实践,提高自己解决问题
的能力。
操作系统实验报告reader-writer

操作系统实验报告实验题目:ReaderWriter实验一.实验目的:1.通过编写和调试程序以加深对进程、线程管理方案的理解2.熟悉Windows多线程程序设计方法二.实验原理:读者-写者允许多个读者同时读一个数据对象,因为读文件不会使数据发生混乱,但不允许一个写者进程与其他读者进程或写者进程同时访问该数据对象。
文件是各个进程能互斥访问临界资源,读者进程和写者进程之间互斥。
在读者进程中,可以有多个读者读数据库,在读者进程的计数要互斥,避免发生错误,同时注意当第一个读者进程读时,一定要封锁写者进程。
当读者进程逐渐撤离时,要针对计数变量进行互斥操作,若当前为最后一个读者进程,读完后应唤醒写者进程。
所以应该分四类可能性:1.读者优先权比写者高,并且不用调配。
2.在一个读者已经占有文件的时候,全体读者的优先权才比写者高3.写者的优先权比读者的优先权高4.所有写者的和所有读者有相同的优先权三.实验代码:DataBaseBuffer:import java.awt.*;public class DataBaseBuffer extends Canvas{int[] readWantQ;int[] writerWantQ;String[] wantQ;int frameDelay = 1560;private int writerID;private int readerCount;private int wantCount;private int readerWantCount, writerWantCount;private int writerCount;private int wn, rn; // the number of readers and writersprivate int readTop, readBottom, writerTop, writerBottom;private int wantTop, wantBottom;private Font font;private FontMetrics fm;private boolean readLock = false;private boolean writeLock = false;public DataBaseBuffer( ){resize(500, 300);setBackground(Color.white);font = new Font("TimesRoman", Font.BOLD, 18);fm = getFontMetrics(font);}public void setSize(int readerN, int writerN){rn = readerN;wn = writerN;readTop = readBottom = writerTop = writerBottom = 0;readerCount = writerCount = readerWantCount = writerWantCount = 0;wantTop = wantBottom = 0;wantCount = 0;writerID = 0;readLock = false;writeLock = false;wantQ = new String[rn+wn];writerWantQ = new int[wn];readWantQ = new int[rn];repaint();}public synchronized void enterQueue(String s, int id){wantQ[wantTop] = s + id;wantTop ++;wantCount ++;repaint();}public synchronized void dequeue(String s, int id ){String str;str = s+id;while(!wantQ[0].equals(str)){try{ wait(); } catch(InterruptedException e) { } }for(int i = 0; i < (wantTop-1); i++){wantQ[i] = wantQ[i+1];}wantTop --;wantCount --;repaint();}public synchronized void changePosition(String s, int id) {String str;String tmp;int pos = 0; //to find the posting of 1st writer String wtr;wtr = s+id;while(!(wantQ[pos].equals(wtr))){pos++;}for(int i = 0; i < wantTop; i++){System.out.println(wantQ[i]);}str = wantQ[pos];for(int i = pos; i > 0; i--){wantQ[i] = wantQ[i-1];}wantQ[0] = str;repaint();for(int i = 0; i < wantTop; i++){System.out.println(wantQ[i]);}}public synchronized boolean hasWriterWant(){return (writerWantCount > 0);}public synchronized boolean hasReaderWant(){return (readerWantCount > 0);}public synchronized void acquireReadLock(ReaderWriterApplet applet, int id){readWantQ[readTop] = id; //nums is the index for readWantQreadTop = (readTop+1) % rn;readerWantCount ++;repaint();notifyAll();enterQueue("R", id);applet.r[id].status = 1; //want inapplet.mc.println(applet.r[id].status, "r", id);try{ applet.r[id].sleep(frameDelay);}catch(InterruptedException e) {}if(applet.writerPriority){while(hasWriterWant() || writeLock){applet.r[id].status = 3;applet.mc.println(applet.r[id].status, "r", id);try{ wait(); } catch(InterruptedException e) { } }//end of while loop}//end of if statementelse if(applet.readerPriority){while(readWantQ[readBottom] != id){try { wait(); } catch(InterruptedException e) {} }changePosition("R",id);}else{applet.r[id].status = 3;applet.mc.println(applet.r[id].status, "r", id);while(!wantQ[wantBottom].equals("R"+id)){try{ wait(); } catch(InterruptedException e) { } }}while(writeLock) //if there is any writer is writing {applet.r[id].status = 3;applet.mc.println(applet.r[id].status, "r", id);try{ wait(); } catch(InterruptedException e) { } }if(readLock == false){readLock = true;notifyAll();}readBottom = (readBottom+1) %rn;readerWantCount --;dequeue("R", id);readerCount ++;repaint();applet.r[id].status = 2;applet.mc.println(applet.r[id].status, "r", id);System.out.println("Reader "+id + "is reading");notifyAll();}public synchronized boolean hasReader(){return (readerCount > 0);}public synchronized void releaseReadLock(ReaderWriterApplet applet,int id){readerCount --;notifyAll();if(!hasReader()){readLock = false;notifyAll();applet.r[id].status = 4;applet.mc.println(applet.r[id].status, "r", id);}repaint();}public synchronized void acquireWriteLock(ReaderWriterApplet applet, int id){writerWantQ[writerTop] = id;writerTop=(writerTop+1)%wn;writerWantCount ++;notifyAll();repaint();enterQueue("W", id);applet.w[id].status = 1; //want inapplet.mc.println(applet.w[id].status, "w", id);try{ applet.w[id].sleep(frameDelay); }catch(InterruptedException e) {}if(applet.writerPriority){while(writerWantQ[writerBottom] != id){try{ wait(); } catch(InterruptedException e) { }}changePosition("W", id);while(readLock || writeLock){try{ wait(); } catch(InterruptedException e) { }}}else if(applet.readerPriority){while(!(wantQ[wantBottom].equals("W"+id)) || hasReaderWant() || readLock || writeLock){try{ wait(); } catch(InterruptedException e) { }}System.out.println("Writer "+ id + " move forward");}else{while(!(wantQ[wantBottom].equals("W"+id))){try{ wait(); } catch(InterruptedException e) { }}while(readLock || writeLock){try{ wait(); } catch(InterruptedException e) { }}}writeLock = true;System.out.println("Writer "+ id+ " Got the lock ******");notifyAll();dequeue("W", id);writerBottom = (writerBottom + 1)%wn;writerID = id;writerWantCount --;writerCount++;notifyAll();repaint();applet.w[id].status = 2;applet.mc.println(applet.w[id].status, "w", id);}public synchronized void releaseWriteLock(ReaderWriterApplet applet, int id){System.out.println("Writer " + id + " released the lock");writerCount --;writerID = 0;writeLock = false;notifyAll();repaint();}public void clear(){writerBottom = writerTop = 0;readBottom = readTop = 0;writerWantCount = 0;readerWantCount = 0;readerCount = 0;writerCount = 0;readLock = writeLock = false;writerWantQ = new int[wn];readWantQ = new int[rn];wantQ = new String[wn+rn];wantTop = wantBottom = 0;}public void paint(Graphics g){int xpos = 630;int ypos = 5;g.setFont(new Font("TimesRoman", Font.BOLD, 11));g.setColor(Color.green);g.draw3DRect(xpos, ypos, 10, 10, true);g.fillRect(xpos, ypos, 10, 10);g.drawString("Reading", xpos+15, ypos+10);g.setColor(Color.red);g.draw3DRect(xpos, ypos+14, 10, 10, true);g.fillRect(xpos, ypos+14, 10, 10);g.drawString("Writing", xpos+15, ypos+25);g.setColor(Color.blue);g.draw3DRect(xpos, ypos+28, 10, 10, true);g.fillRect(xpos, ypos+28, 10, 10);g.drawString("Empty", xpos+15, ypos+40);g.setFont(new Font("TimesRoman", Font.BOLD, 14));g.setColor(Color.blue);xpos = 40;ypos = 50;g.drawString("Waiting Queue", xpos-5, ypos-20);int i = wantBottom;for(int j = 0; j < wantCount; j++){if( wantQ[i].equals("W1") || wantQ[i].equals("W2")||wantQ[i].equals("W3")|| wantQ[i].equals("W4")||wantQ[i].equals("W5")){g.setColor(Color.red);g.drawString(wantQ[i], xpos+450-30*j, ypos-18);g.draw3DRect(xpos+445-30*j, ypos-35, 28, 28, true);}if( wantQ[i].equals("R1") || wantQ[i].equals("R2")||wantQ[i].equals("R3")|| wantQ[i].equals("R4")||wantQ[i].equals("R5")){g.setColor(Color.green);g.drawString(wantQ[i], xpos+450-30*j, ypos-18);g.draw3DRect(xpos+445-30*j, ypos-35, 28, 28, true);}i = (i+1) % (wn+rn);}if(readLock) g.setColor(Color.green);else if(writeLock) g.setColor(Color.red);else g.setColor(Color.blue);g.draw3DRect(xpos+250, ypos+20, 100, 100, true);g.fillRect(xpos+250, ypos+20, 100, 100);if(readLock){g.setColor(Color.black);g.drawString("Reading", xpos + 270, ypos+60);}else if(writeLock){g.setColor(Color.black);g.drawString("W " +Integer.toString(writerID), xpos + 280,ypos+45);g.drawString("Writing", xpos + 270, ypos+60);}}}MessageCanvas:import java.awt.*;class MessageCanvas extends Canvas{private Font font;private FontMetrics fm;private int[] writerStatus;private int[] readerStatus;private int msgHeight;private int msgWidth;private int pn, cn;private int frameDelay = 256;public MessageCanvas( ){resize(size().width, 50);setBackground(Color.green);font = new Font("TimesRoman", 1, 18);fm = getFontMetrics(font);msgHeight = fm.getHeight();}public void setMessage(int writerN, int readerN) {pn = writerN;cn = readerN;writerStatus = new int[pn+1];readerStatus = new int[cn+1];repaint();}void println(String s){msgWidth = fm.stringWidth(s);repaint();}void println(int s, String st, int id){if(st.equals("w"))writerStatus[id] = s;elsereaderStatus[id] = s;repaint();}void println(int s, int number, String st, int id){if(st.equals("w")){writerStatus[id] = s;}else{readerStatus[id] = s;}repaint();}public void paint(Graphics g){g.setFont(font);int xpos = 60;int ypos = 40;g.drawString("Status of Readers: ", 60, 20);g.drawString("Status of Writers: ", 360, 20);g.setFont(new Font("TimesRoman", 1, 14));for(int i=1; i<=cn;i++){g.setColor(Color.black);g.drawString("R" + i, xpos, ypos+(15*i+10*(i-1)));if(readerStatus[i] == 0){g.setColor(Color.yellow);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Sleeping ...", xpos+120, ypos+(15*i + 10*(i-1)));}else if (readerStatus[i] == 1){g.setColor(Color.gray);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Want to read", xpos+120, ypos+(15*i + 10*(i-1)));}else if (readerStatus[i] == 3){g.setColor(Color.gray);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Waiting in the queue", xpos+120, ypos+(15*i + 10*(i-1)));}else if (readerStatus[i] == 2){g.setColor(Color.blue);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Reading...", xpos+120, ypos+(15*i + 10*(i-1)));}}xpos = 360;ypos = 40;for(int i=1; i<=pn; i++){g.setColor(Color.black);g.drawString("W" + i, xpos, ypos+(15*i+10*(i-1)));if(writerStatus[i] == 0){g.setColor(Color.yellow);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Sleeping ...", xpos+120, ypos+(15*i + 10*(i-1)));}else if (writerStatus[i] == 1){g.setColor(Color.gray);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Waiting in the queue", xpos+120, ypos+(15*i + 10*(i-1)));}else if (writerStatus[i] == 2){g.setColor(Color.blue);g.fillOval(xpos+60, ypos+(2*i+22*(i-1)), 18, 18);g.drawString("Writing ...", xpos+120, ypos+(15*i + 10*(i-1)));}}}}Reader:public class Reader extends Thread{private DataBaseBuffer buffer;private ReaderWriterApplet tapplet;private int cid;int delay = 6500;int status = 0;public Reader(ReaderWriterApplet applet, DataBaseBuffer db, int id){ buffer = db;tapplet = applet;cid = id;}public void run(){while(true){try{status = 0;tapplet.mc.println(status, "r", cid);sleep((int) (Math.random()*delay));buffer.acquireReadLock(tapplet, cid);sleep((int) (Math.random()*delay));buffer.releaseReadLock(tapplet, cid);} catch(InterruptedException e){System.err.println("Reader Execption " + e.toString());}}}}ReaderWriterApplet:import java.awt.*;import java.awt.event.*;import java.util.*;import java.applet.Applet;import ng.*;public class ReaderWriterApplet extends Applet{private ReaderWriterApplet applet = this;private DataBaseBuffer myBuffer;private int buffersize;private Button fastButton, slowButton, stopButton, startButton, pauseButton, continueButton;private Button stopReaderButton, stopWriterButton;private Panel buttonPanel, priorityPanel, namePanel;private Choice priority, reader, writer;private Thread at;private int readerN = 1;private int writerN = 1;boolean readerPriority = false;boolean writerPriority = false;boolean samePriority = true; //default priority of readers and writers MessageCanvas mc;Reader[] r;Writer[] w;synchronized void startPushed() {notify();}synchronized void stopPushed() {notify();}public void init() {myBuffer = new DataBaseBuffer();mc = new MessageCanvas();resize(800, 600);setLayout(new GridLayout(3, 1));add(myBuffer);add(mc);buttonPanel = new Panel();priorityPanel = new Panel();namePanel = new Panel();Panel bPanel = new Panel(); // to hold all buttons and the labels bPanel.setFont(new Font("TimesRoman", Font.BOLD, 14));bPanel.setLayout(new GridLayout(3, 1));buttonPanel.add(startButton = new Button("START"));buttonPanel.add(stopButton = new Button("STOP"));buttonPanel.add(pauseButton = new Button("PAUSE"));buttonPanel.add(continueButton = new Button("CONTINUE"));buttonPanel.add(fastButton = new Button("FASTER"));buttonPanel.add(slowButton = new Button("SLOWER"));Panel choicePanel = new Panel(); //to hold all the choice boxespriority = new Choice();priority.addItem("Same Priority");priority.addItem("Writers Have Priority");priority.addItem("Readers Have Priority");priority.select("Same Priority");Label priorityLabel = new Label("Priority", 2);priorityLabel.setBackground(Color.lightGray);priorityPanel.add(priorityLabel);priorityPanel.add(priority);choicePanel.add(priorityPanel);reader = new Choice();for(int i = 0; i <=5; i++){reader.addItem(Integer.toString(i));}reader.select("1");Label readerLabel = new Label("Number of Readers", 2);readerLabel.setBackground(Color.lightGray);Panel readerPanel = new Panel();readerPanel.add(readerLabel);readerPanel.add(reader);writer = new Choice();for(int i = 0; i<=5; i++){writer.addItem(Integer.toString(i));}writer.select("1");Label writerLabel = new Label("Number of Writers", 2);writerLabel.setBackground(Color.lightGray);Panel writerPanel = new Panel();writerPanel.add(writerLabel);writerPanel.add(writer);Label nameLabel = new Label("Readers/Writers Animation");nameLabel.setFont(new Font("TimesRoman", Font.BOLD, 18));nameLabel.setForeground(Color.blue);namePanel.add(nameLabel);choicePanel.add(readerPanel);choicePanel.add(writerPanel);bPanel.add(choicePanel);bPanel.add(buttonPanel);bPanel.add(namePanel);add(bPanel);}public boolean action(Event evt, Object arg){if(evt.target == priority){if(arg.equals("Writers Have Priority")){writerPriority = true;readerPriority = false;samePriority = false;}else if(arg.equals("Readers Have Priority")) {readerPriority = true;writerPriority = false;samePriority = false;}else{readerPriority = false;writerPriority = false;samePriority = false;}return true;}else if(evt.target == reader){readerN = Integer.parseInt(arg.toString());return true;}else if(evt.target == writer){writerN = Integer.parseInt(arg.toString());return true;}else if(arg.equals("FASTER")){int newDelay;if(readerN != 0) newDelay = r[1].delay;else newDelay = w[1].delay;newDelay /= 2;newDelay = newDelay < 100 ? 100: newDelay;for(int i = 1; i <= readerN; i++){r[i].delay = newDelay;for(int i = 1; i <= writerN; i++){w[i].delay = newDelay;}return true;}else if(arg.equals("SLOWER")){int newDelay;if(readerN !=0) newDelay = w[1].delay;else newDelay = r[1].delay;newDelay *= 2;for(int i = 1; i <= readerN; i++){r[i].delay = newDelay;}for(int i = 1; i <= writerN; i++){w[i].delay = newDelay;}return true;}else if(arg.equals("PAUSE")){for(int i = 1; i <= readerN; i++){r[i].suspend();}for(int i = 1; i <= writerN; i++){w[i].suspend();}fastButton.setEnabled(false);slowButton.setEnabled(false);return true;}else if(arg.equals("CONTINUE")){for(int i = 1; i <= readerN; i++){if(r[i].isAlive()) r[i].resume();}for(int i = 1; i <= writerN; i++)if(w[i].isAlive()) w[i].resume();}fastButton.setEnabled(true);slowButton.setEnabled(true);return true;}else if(arg.equals("START")){r = new Reader[readerN+1]; //Reader[0] is a dummy slotw = new Writer[writerN+1];System.out.println("readers: "+readerN+" writers: " + writerN);mc.setMessage(writerN, readerN);myBuffer.setSize(readerN, writerN);for(int i = 1; i <= readerN; i++){r[i] = new Reader(applet, myBuffer, i);}for(int i = 1; i <= writerN; i++){w[i] = new Writer(applet, myBuffer, i);}for(int i = 1; i <= writerN; i++){w[i].start();}for(int i = 1; i <= readerN; i++){r[i].start();}fastButton.setEnabled(true);slowButton.setEnabled(true);startButton.setEnabled(false);reader.setEnabled(false);writer.setEnabled(false);priority.setEnabled(false);applet.startPushed();return true;}else if(arg.equals("STOP")){for(int i = 1; i <= readerN; i++){if(r[i].isAlive())r[i].stop();r[i] = null;}for(int i = 1; i <= writerN; i++){if(w[i].isAlive())w[i].stop();w[i] = null;}applet.stopPushed();startButton.setEnabled(true);fastButton.setEnabled(true);slowButton.setEnabled(true);reader.setEnabled(true);writer.setEnabled(true);priority.setEnabled(true);if(at != null) at.stop();at = null;return true;}else{ return false;}}}Writer:public class Writer extends Thread{private DataBaseBuffer buffer;private ReaderWriterApplet tapplet;private int id;int delay = 6500;int status = 0;public Writer(ReaderWriterApplet applet, DataBaseBuffer db, int id){ buffer = db;tapplet = applet;this.id = id;}public void run(){while(true){try{status = 0;tapplet.mc.println(status, "w", id);sleep((int)(Math.random()*delay));buffer.acquireWriteLock(tapplet, id);sleep((int) (Math.random()*delay));buffer.releaseWriteLock(tapplet, id);} catch(InterruptedException e){System.err.println("Execption " + e.toString());}}}}四.实验结果:运行如下:。
读者写者问题-操作系统实验报告 (1)

实验内容1、定义一个数据缓存buffer 及用于实现同步互斥的信号量。
2、定义一个读者函数:● 当有写者在占用buffer 时,读者应该等待,直到写者不再使用该buffer 。
● 当有其他读者在占用buffer 时,读者可对buffer 进行读取操作。
● 当buffer 中有数据时,则从其中读取一个数据,并显示然后退出。
● 当buffer 中没有数据时,应等待,直到buffer 中有数据可读。
3、定义一个写者函数● 当有读者在占用buffer 时,写者应该等待,直到所有的读者都退出为止。
● 当有其他写者占用buffer 时,该写者应该等待,直到占用buffer 的写者退出为止。
● 当buffer 有空闲时,写者应该在buffer 中写入一个数据并退出。
● 当buffer 满时,写者应该等待,直到buffer 有空闲为止。
4、定义主函数,在其中可以任意创建读者与写者。
● 可根据用户输入创建读者或写者进程(线程)。
5、用户界面2. 写者: 开始 读出的内容: 1. 读者:开始 结束 2 1 读者队列等待结束写出的内容: Hello world !结束实验当堂所要完成事情列表:1.调试程序使其在读者优先模式下可以运行并且能实现基本的功能得出正确的结果:能够实现读写互斥,写写互斥,读读不互斥,一个进程结束能够唤醒等待队列中的进程(先读者队列后写着队列)2.根据实验要求完善功能:由用户决定写者向缓冲区中写入的内容,读者能够读出并显示出来;当缓冲区中没有数据时,读者要等待,直到缓冲区中有数据才能读3.根据“读者优先”加以改变,增加一个“写者优先”模式,并且由用户来选择模式源代码:#include<stdio.h>#include<stdlib.h>int rcount=0;//正在读的读者数量int wcount=0;//写者队列中等待写操作的写者数量int read_id=0;//读进程号int write_id=0;//写进程号int w=1;//读写互斥信号量char temp[300] = {'\0'};int choice; //用户选择读者优先OR写者优先int sign; //标识temp空的信号量 0表示temp空void WFwakeup();void RFwakeup();struct rqueue{//读者等待队列int readers[200];int index;}rq;struct wqueue{//写者等待队列int writers[200];int index;}wq;/*void first(){ //初始化int i;rq.index = 0;wq.index = 0;for(i = 0;i<20;i++){rq.readers[i] = 0;wq.writers[i] = 0;}}*///*******************************************读进程读操作void read(){int i = 0;read_id++;if(rcount == 0){//当前没有读进程在读可能有写进程在写可能CPU空闲if(w==1) {//如果CPU空闲,读者拿到CPUw--;// 相当于一个P操作rcount++;if(temp[0] == '\0'){sign = 0;if(choice == 1){rq.readers[rq.index++]=read_id;//将读者进程加入等待队列RFwakeup();return;}else{rq.readers[rq.index++]=read_id;//将读者进程加入等待队列WFwakeup();return;}}//ifprintf("读者%d正在读\n",read_id);for(i = 0;i < 300;i++){//读取temp内容即写者写的内容if(temp[i] == '\0'){printf("\n");return;}//ifprintf("%c",temp[i]);}//for}//ifelse{//写者线程正在执行printf("!有写者在写不能读!\n");rq.readers[rq.index++]=read_id;//将读者进程加入等待队列}//else}//ifelse{//rcount !=1 则知道当前已经有读者在读,读读不互斥,则这个读者可以直接进来了读printf("读者%d正在读\n",read_id);for(i = 0;i < 300;i++){if(temp[i] == '\0'){printf("\n");return;}printf("%c",temp[i]);}//for}//else}//***************************写进程写操作void write(){write_id++;if(w == 0){if(rcount != 0 ){//有读者进程在执行printf("!有读者在读不能写!\n");wq.writers[wq.index++]=write_id;//将写者进程加入等待队列wcount++;return;}if(rcount == 0 ){//rcount == 0则当前无读者,但w = 0,所以有写者在写printf("!有写者在写不能写!\n");wq.writers[wq.index++]=write_id;//将写者进程加入等待队列wcount++;return;}}if(w == 1){w--;printf("写者%d正在写\n请输入要写的内容",write_id);scanf("%s",temp);//while}//if}//************************读者优先时唤醒进程void RFwakeup(){int i = 0;int j = 0;int m,n;m = rq.index;// n = wq.index;if(rcount == 0){//当前无读进程,是写者在写 --》停止运行写进程bool reader_wait=false;w=1;printf("写者已经写完\n");sign = 1;//temp中已经有内容要置1for(i=0;i<=m;i++){// i ndex为当前读者队列中的等待进程数if(rq.readers[i]!=0){reader_wait=true; //确实有读者在等待printf("等待的读者%d正在读\n",rq.readers[i]);w = 0;for(j = 0;j < 300;j++){if(temp[j] == '\0'){printf("\n");break;}//ifprintf("%c",temp[j]);}//forrq.readers[i]=0;rcount++;rq.index--;}//if}//forif(!reader_wait){//没有读者等待,看是否有写者等待for(int i=0;i<=wq.index;i++){//检查写者等待队列if(wq.writers[i]!=0){w = 0;printf("等待的写者%d正在写\n请输入要写入的内容",wq.writers[i]);scanf("%s",temp);wq.writers[i]=0;wcount--;break;}//if}//for}//if// return;}//ifelse{//rcount != 0读者正在读,stop读此时若有等待必为写者rcount=0;w = 1;if(sign == 0){printf("缓冲区空等待写者\n");return;}else{printf("读者已经读完\n");for(int i=0;i<=wq.index;i++){// 检查写者等待队列if(wq.writers[i]!=0){w = 0;printf("等待的写者%d正在写\n请输入要写入的内容",wq.writers[i]);scanf("%s",temp);wq.writers[i]=0;wcount--;break;}//if}//for}}//else}//******************************************写者优先唤醒void WFwakeup(){int i = 0;int j = 0;int m,n;m = rq.index;//n = wq.index;if(rcount == 0){//当前无读进程,是写者在写 --》停止运行写进程bool writer_wait=false;w=1;printf("写者已经写完\n");sign = 1;//temp中已经有内容要置1for(i=0;i<=wq.index;i++){// index为当前写者队列中的等待进程数if(wq.writers[i]!=0){writer_wait=true; //确实有写者在等待printf("等待的写者%d正在写\n 请输入要写的内容\n",wq.writers[i]);w = 0;scanf("%s",temp);wq.writers[i]=0;wcount--;break;}}if(!writer_wait){//没有xie者等待,看是否有du者等待for(int i=0;i<=m;i++){//检查写者等待队列if(rq.readers[i]!=0){w = 0;printf("等待的读者%d正在读\n",rq.readers[i]);for(j = 0;j < 300;j++){if(temp[j] == '\0'){printf("\n");rq.index--;break;}//ifprintf("%c",temp[j]);}//forrq.readers[i]=0;rcount++;}//if}//for}//if// return;}//ifelse{//rcount != 0读者正在读,stop读此时若有等待必为写者rcount=0;w = 1;printf("读者已经读完\n");for(int i=0;i<=wq.index;i++){// 检查写者等待队列if(wq.writers[i]!=0){w = 0;printf("等待的写者%d正在写\n请输入要写入的内容",wq.writers[i]);scanf("%s",temp);wq.writers[i]=0;wcount--;break;}//if}//for}}void menu1(){char i;printf(" 1-创建读者进程\n 2-创建写者进程\n 3-结束当前执行的进程\n 4-退出程序\n");printf("*******************************************\n");do{printf("当前队列中有读者: %d个写者: %d个\n",rq.index,wcount);printf("*******************************************\n");printf(" ----->");scanf("%s",&i);switch(i){case '1':read();break;case '2':write();break;case '3':RFwakeup();break;case '4':exit(0);default:printf("输入错误请重新输入\n");}}while(true);}void menu2(){char i;printf(" 1-创建读者进程\n 2-创建写者进程\n 3-结束当前执行的进程\n 4-退出程序\n");printf("*******************************************\n");do{printf("当前队列中有读者: %d个写者: %d个\n",rq.index,wcount);printf("*******************************************\n");printf(" ----->");scanf("%s",&i);switch(i){case '1':read();break;case '2':write();break;case '3':WFwakeup();break;case '4':exit(0);default:printf("输入错误请重新输入\n");}}while(true);}void main(){printf("*************************************************** ***********************\n");printf(" 20092104实验一\n 1.读者优先\n 2.写者优先\n");scanf("%d",&choice);while(1){if(choice == 1)menu1();if(choice == 2)menu2();if(choice != 1 && choice != 2){printf("输入错误请重新输入\n");scanf("%d",&choice);}}}实验流程图:N Y开始 读者优先 写者优先 读操作 写操作 是否有读者在读进行读操作 YCPU 是否空闲 缓冲区是否为空有写者 读者入队 N Y 入读者等待队列 调用读者优先唤醒 读操作 N 是否有读者在读 有读者 写者入队 Y N Cpu 是否空闲进行写操作 有写者,写操作入队 YN 退出 结束 读者优先唤醒 写者优先唤醒核心部分设计思路:读者优先唤醒当前有无读者在读有无读者等待N有无写者等待N 读者出队进行读操作直到读者队空Y进行写操作 YN 返回Y缓冲区是否为空YN写者优先唤醒当前有无读者在读有无写者等待N有无读者等待N 写者出队进行写操作直到写者队空Y进行读操作直到读者队列为空YN 返回YN写者队列是否为空进行写操作直到写者队列为空Y有读者说明若有等待必为写者分别用两个队列来存放等待的读者进程和写者进程,一个进程结束后就要将因他阻塞的进程唤醒,如果是读者优先,则先检查读者进程,如果发现读者进程不为空,就进行读操作,直到读者进程为空,才进行写操作;同理,如果是写者优先,则先检查写进程,如果发现写者进程不为空,就进行写操作,直到写者进程为空,才进行读操作。
《操作系统》实验报告(4)

{
int p1,p2,i;
int *fp;
fp = fopen("family.txt","w+"); /*打开文件family.txt*/
if(fp==NULL)
{
printf("Fail to create file");
exit(-1);
}
while((p1=fork())==-1); /*创建子进程p1*/
{
printf( "Child process1is killed by parent!!\n" );
}
/*fork second child process*/
if ( ( pid2=fork() ) == 0 )
{
printf( "Child process 2 is killed by parent!!\n" );
{
lockf(*fp,1,0); /*加锁*/
for(i=0;i<5;i++)
{
fprintf(fp,“Child2 %d\n”,i);
sleep(1);
}
lockf(*fp,0,0); /*解锁*/
}
else
{
lockf(*fp,1,0); /*加锁*/
for(i=0;i<5;i++)
{
fprintf(fp,"Parent %d\n",i);
Child process 1 is killed by parent!!
Child process 2 is killed by parent!!
操作系统Lab2实验报告

深入学习 操作系统的原理和实 现细节,包括进程通 信、死锁处理、虚拟 化技术等。
实践应用
希望将所学的操作系 统知识应用到实际项 目中,提高自己的实 践能力。
持续学习
随着技术的不断发展 ,操作系统也在不断 更新和进步,需要保 持持续学习的态度。
探索新领域
对于新兴的操作系统 领域,如云操作系统 、物联网操作系统等 ,也希望有所涉猎和 探索。
学生将了解操作系统内核的组成和功能,以及操作系统如何通过内核 实现各种基本功能。
学生将通过实验深入了解操作系统的内部实现细节,提高自己对操作 系统设计和实现的认知水平。
02
实验内容
进程管理实验
总结词
理解进程状态及其转换、进程控制块PCB的组成、进程调度算法。
详细描述
通过实验,我们深入了解了进程的概念、状态及其转换。进程控制块PCB的组成,包括进程标 识符、进程状态、优先级、CPU寄存器内容等信息。此外,我们还学习了进程调度算法,如先 来先服务、最短作业优先、优先级调度等,并进行了模拟实验。
THANKS
感谢观看
操作系统Lab2实验 报告
汇报人:
202X-01-08
目录
• 实验目的 • 实验内容 • 实验结果与分析 • 问题与改进建议 • 总结与展望
01
实验目的
理解操作系统的基本概念
01
掌握核心概念
02
操作系统是计算机系统的核心软件,负责管理计算机硬件和软件资源 ,为用户提供便利的操作界面和高效的服务。
03
操作系统具有并发性、虚拟性、异步性和随机性的特点,这些特点决 定了操作系统在计算机系统中的重要地位和作用。
04
操作系统的基本功能包括进程管理、内存管理、文件管理和设备管理 ,这些功能是操作系统实现其核心目标的基础。
操作系统实验报告心得体会范文大全(8篇)

操作系统实验报告心得体会范文大全(8篇)操作系统实验报告心得体会范文大全篇一:通过这一学期学习,才慢慢接触专业课。
刚开始觉得挺难得我都有点不想学这个专业了,慢慢的我觉得有趣多了。
虽然我学的不是很好,最起码我能给自己装系统了。
我给自己的电脑装过window7、xp系统。
从一开始连个cmos设置都不会进去,到现在能装各种机型的系统。
让我最高兴的事是我会建立网站了,以及能制作出复杂点的,漂亮的网页了。
从刚开始学装windowserver20xx时,我真的懵懵懂懂的,那开始是真的不想学这个专业了,那段时间还学java编程,我真的快崩溃了,后悔自己干嘛学这个专业,我根本就是没有天赋,感觉大学这四年完蛋了,大一大二还没有感觉,现在真实的感受到了,但后来发现,我是越来越感觉有兴趣了,只要肯付出课后肯钻研,就一定会有一点收获的。
通过这次网页课程设计激发学习兴趣,调动学习的自觉性,自己动脑、动手,动口,运用网络资源,结合教材及老师的指导,通过自身的实践,创作出积聚个人风格、个性的个人网页。
总体来说,整个学期的学习过程,我学会了很多知识,在此次网页设计中,我充分利用了这次设计的机会,全心全意投入到网页世界,去不断的学习,去不断的探索;同时去不断的充实,去不断的完善自我,在网络的天空下逐渐的美化自己的人生!做好页面,并不是一件容易的事,它包括个人主页的选题、内容采集整理、图片的处理、页面的排版设置、背景及其整套网页的色调等很多东西。
本次课程设计不是很好,页面过于简单,创新意识反面薄弱,这是我需要提高的地方。
需要学的地方还有很多,需要有耐心、坚持,不断的学习,综合运用多种知识,才能设计出好的web页面。
总体来说,通过这次的对网页和网站课程设计,有收获也有遗憾、不足的地方,但我想,我已经迈入了网页设计的大门,只要我再认真努力的去学习,去提高,凭借我对网页设计的热情和执着,我将来设计出的网页会更加专业,更完善。
操作系统实验报告心得体会范文大全篇二:转眼间,学习了一个学期的计算机操作系统课程即将结束。
操作系统实验报告_读者写者问题

void WP_WriterThread(void * p) //---------------------------写者优先--写者线程
{
HANDLE h_Mutex1;//互斥变量
h_Mutex1 = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutexl");
HANDLE h_Mutex2;
h_Mutex2 = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex2");
DWORD wait_for_mutex1; //等待互斥变量所有权
};
void RP_ReaderThread(void * p) //---------------------------读者优先--读者线程
{
HANDLE h_Mutex;//互斥变量
//OpenMutex函数功能:为现有的一个已命名互斥体对象创建一个新句柄
h_Mutex = OpenMutex(MUTEX_ALL_ACCESS,FALSE,"mutex_for_readcount");
(附注释)
#include "stdafx.h"
#include"windows.h"
#include<conio.h>
#include<stdlib.h>
#include<fstream.h>
#include<io.h>
#include<string.h>
#include<stdio.h>
#define READER 'R' //读者
操作系统上机实验报告

操作系统上机实验报告学院:计算机科学与技术学院专业:计算机科学与技术学号:姓名:读者-写者的读写限制(包括读者优先和写者优先)1)写-写互斥,即不能有两个写者同时进行写操作2)读-写互斥,即不能同时有一个读者在读,同时却有一个写者在写3)读读允许,即可以有2个以上的读者同时读读者优先的限制:如果一个读者申请读操作时,已经有一个读者在读,则该读者可以直接读写者优先的限制:如果一个读者申请读操作时,有写者在等待访问共享资源时,则该读者要等到没有写者处于等的状态时才能开始读操作代码部分:#include <sys/types.h>#include <sys/ipc.h>#include <sys/sem.h>#include <sys/shm.h>#include <signal.h>#include <unistd.h>#include <stdarg.h>#include <assert.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <time.h>/*** @struct SHM_ACCESS* @brief 读者写者访问控制结构*/typedef struct _SHM_ACCESS {int reader_count; /**< 读者计数器 */int reader_mutex; /**< 读者互斥量 */int writer_mutex; /**< 写者互斥量 */} SHM_ACCESS;typedef struct _READER_WRITER_SHM {SHM_ACCESS shm_access;int shm_reader;int shm_writer;} READER_WRITER_SHM;static sig_atomic_t term_flag = 0;intlogv(const char *fmt, ...){int n;struct timeval tv;struct tm lt;char buf[14];va_list ap;gettimeofday(&tv, 0);lt = *localtime(&_sec);strftime(buf, sizeof(buf), "%H:%M:%S.", <);snprintf(buf + 9, sizeof(buf) - 9, "%03d", (int)(_usec / 1000)); n = printf("%s ", buf);va_start(ap, fmt);n += vprintf(fmt, ap);va_end(ap);return n;}/** System V IPC 函数的简化接口*/intsem_p(int semid){int rc;struct sembuf buf;buf.sem_num = 0;buf.sem_op = -1;buf.sem_flg = SEM_UNDO;for (;;) {rc = semop(semid, &buf, 1); if (0 == rc)break;if (rc < 0) {if (EINTR == errno)continue;else {assert(0);}}}}intsem_v(int semid){int rc;struct sembuf buf;buf.sem_num = 0;buf.sem_op = +1;buf.sem_flg = SEM_UNDO;for (;;) {rc = semop(semid, &buf, 1); if (0 == rc)break;if (rc < 0) {if (EINTR == errno)continue;else {assert(0);}}}return rc;}intsem_get(const char *path, int id){int semid;key_t semkey;int rc;union semun {int val;struct semid_ds *buf;unsigned short *array;} arg;semkey = ftok(path, id);if ((key_t)-1 == semkey) {return (-1);}semid = semget(semkey, 1, IPC_CREAT | SEM_R | SEM_A); if (semid < 0)return semid;arg.val = 1;rc = semctl(semid, 0, SETVAL, arg);assert(0 == rc);return semid;}intsem_del(const char *path, int id){int semid;key_t semkey;int rc;semkey = ftok(path, id);if ((key_t)-1 == semkey) {return (-1);}semid = semget(semkey, 1, SEM_R | SEM_A);return sem_rmid(semid);}intsem_rmid(int semid){int rc;rc = semctl(semid, 0, IPC_RMID);return rc;}intshm_get(const char *path, int id, size_t size){int shmid;key_t semkey;semkey = ftok(path, id);if ((key_t)-1 == semkey) {return (-1);}shmid = shmget(semkey, size, IPC_CREAT | SHM_R | SHM_W); if (shmid < 0)return shmid;return shmid;}/** 共享内存读写控制函数*/intLockShmForWrite(SHM_ACCESS *p_access){sem_p(p_access->writer_mutex);return (0);}intUnLockShmForWrite(SHM_ACCESS *p_access){sem_v(p_access->writer_mutex);return (0);}intLockShmForRead(SHM_ACCESS *p_access){sem_p(p_access->reader_mutex);p_access->reader_count++;logv("reader_count = %d\n", p_access->reader_count); if (1 == p_access->reader_count) {/* 第一个读进程 */sem_p(p_access->writer_mutex);}sem_v(p_access->reader_mutex);return (0);}intUnLockShmForRead(SHM_ACCESS *p_access){sem_p(p_access->reader_mutex);p_access->reader_count--;logv("reader_count = %d\n", p_access->reader_count); if (0 == p_access->reader_count) {/* 最后一个读进程 */sem_v(p_access->writer_mutex);}sem_v(p_access->reader_mutex);return (0);}void*shm_at(int shmid){return shmat(shmid, NULL, 0);}intshm_dt(const void *shmaddr){return shmdt(shmaddr);}intshm_rmid(int shmid){return shmctl(shmid, IPC_RMID, NULL);}void(*Signal(int sig, void (*func)(int)))(int){struct sigaction act, oact;act.sa_handler = func;sigemptyset(&act.sa_mask);act.sa_flags = 0;#ifdef SA_INTERRUPTact.sa_flags |= SA_INTERRUPT;#endifif (sigaction(sig, &act, &oact) < 0)return(SIG_ERR);return(oact.sa_handler);}#define KEY_FILE "KEY_FILE"intstarter(void){int shmid;int semid;READER_WRITER_SHM *ptr;shmid = shm_get(KEY_FILE, 1, sizeof(READER_WRITER_SHM)); ptr = (READER_WRITER_SHM *)shm_at(shmid);semid = sem_get(KEY_FILE, 2);ptr->shm_access.reader_mutex = semid;ptr->shm_access.reader_count = 0;semid = sem_get(KEY_FILE, 3);ptr->shm_access.writer_mutex = semid;return 0;}intcleaner(void){int shmid;int semid;READER_WRITER_SHM *ptr;sem_del(KEY_FILE, 3);sem_del(KEY_FILE, 2);shmid = shm_get(KEY_FILE, 1, sizeof(READER_WRITER_SHM)); shm_rmid(shmid);return 0;}voidsig_term(int sig){term_flag++;}voidsig_intr(int sig){}intreader(void){int shmid;pid_t pid;READER_WRITER_SHM *ptr;shmid = shm_get(KEY_FILE, 1, sizeof(READER_WRITER_SHM)); ptr = (READER_WRITER_SHM *)shm_at(shmid);pid = getpid();srand(time(0) + pid);while (!term_flag) {sleep(rand() % 20);logv("reader-%10d come\n", (int)pid);LockShmForRead(&ptr->shm_access);logv("reader-%10d read begin\n", (int)pid);sleep(rand() % 10);logv("reader-%10d read end\n", (int)pid);UnLockShmForRead(&ptr->shm_access);}return 0;}intwriter(void){int shmid;pid_t pid;READER_WRITER_SHM *ptr;shmid = shm_get(KEY_FILE, 1, sizeof(READER_WRITER_SHM)); ptr = (READER_WRITER_SHM *)shm_at(shmid);pid = getpid();srand(time(0) + pid);while (!term_flag) {sleep(rand() % 20);logv("writer-%10d come\n", (int)pid);LockShmForWrite(&ptr->shm_access);logv("writer-%10d write begin\n", (int)pid);sleep(rand() % 10);logv("writer-%10d write end\n", (int)pid);UnLockShmForWrite(&ptr->shm_access);}return 0;}#define M 8#define N 2intmain(int argc, char *argv[]) {int i, m, n;pid_t pid[M + N];m = M, n = N;Signal(SIGTERM, &sig_term);starter();for (i = 0; i < m; i++) { pid[i] = fork();if (pid[i] == 0) {reader();exit(0);} else {continue;}}for (i = 0; i < n; i++) { pid[i + m] = fork();if (pid[i + m] == 0) { writer();exit(0);} else {continue;}}Signal(SIGINT, &sig_intr);pause();for (i = 0; i < M + N; i++) kill(pid[i], SIGTERM);for (i = 0; i < M + N; i++)waitpid(pid[i], NULL, 0);cleaner();return 0;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
东华大学计算机学院操作系统实验报告实验名称:读者写者问题姓名:姜元杰学号:111310228班级:计算机1102指导老师:李继云报告日期:2013/10/12一、实验概述1.实验目标在Windows系统平台下,了解Windows编程基本知识,通过创建线程等一系列操作实现进程同步经典问题——读者写者问题。
2.实验要求在Windows7环境下,创建一个控制台进程,此进程包含n个线程。
用这n 个线程来表示n个读者或写者。
每个线程按相应测试数据文件(后面有介绍)的要求进行读写操作。
用信号量机制分别实现读者优先和写者优先的读者-写者问题。
读者-写者问题的读写操作限制(包括读者优先和写者优先):1)写-写互斥,即不能有两个写者同时进行写操作。
2)读-写互斥,即不能同时有一个线程在读,而另一个线程在写。
,3)读-读允许,即可以有一个或多个读者在读。
读者优先的附加限制:如果一个读者申请进行读操作时已有另一个读者正在进行读操作,则该读者可直接开始读操作。
写者优先的附加限制:如果一个读者申请进行读操作时已有另一写者在等待访问共享资源,则该读者必须等到没有写者处于等待状态后才能开始读操作。
运行结果显示要求:要求在每个线程创建、发出读写操作申请、开始读写操作和结束读写操作时分别显示一行提示信息,以确定所有处理都遵守相应的读写操作限制。
二、实验内容1.设计思路通过仔细分析问题,实验实现内容分别为读者优先部分与写者优先部分。
通过建立统一的线程数组存储所有待创建线程,并在系统后台分别存于可以将所有读者和所有写者分别存于一个读者等待队列和一个写者等待队列中,每当读允许时,就从读者队列中释放一个或多个读者线程进行读操作;每当写允许时,就从写者队列中释放一个写者进行写操作。
通过程序代码实现读读允许,读写互斥,写写互斥。
对于读者优先部分,引入Mutex信号量和临界区对象RP_Writer实现。
读者优先指的是除非有写者在写文件,否则读者不需要等待。
所以可以用一个整型变量read_Count记录当前的读者数目,用于确定是否需要释放正在等待的写者线程(当read_Count=O时,表明所有的读者读完,需要释放写者等待队列中的一个写者)。
每一个读者开始读文件时,必须修改read_Count变量。
因此需要一个互斥对象Mutex来实现对全局变量read_Count修改时的互斥。
另外,为了实现写-写互斥,需要增加一个临界区对象RP_Writer。
当写者发出写请求时,必须申请临界区对象的所有权。
通过这种方法,也可以实现读-写互斥,当read_ Count=l 时(即第一个读者到来时),读者线程也必须申请临界区对象的所有权。
当读者拥有临界区的所有权时,写者阻塞在临界区对象RP_Writer上。
当写者拥有临界区的所有权时,第一个读者判断完"read_Count==1"后阻塞在write上,其余的读者由于等待对read_Count的判断,阻塞在Mutex上。
对于写者部分,与读者优先类似;不同之处在于一旦一个写者到来,它应该尽快对文件进行写操作,如果有一个写者在等待,则新到来的读者不允许进行读操作。
为此应当添加一个整型变量write_Count,用于记录正在等待的写者的数目,当write_Count=0时,才可以释放等待的读者线程队列。
增加一个互斥对象Mutex3,维护对全局变量write_Count的互斥修改。
为了实现写者优先,应当添加一个临界区对象CS_Reader,当有写者在写文件或等待时,读者必须阻塞在CS_Reader上,同时读者线程除了要对全局变量read_Count实现操作上的互斥外,还必须有一个互斥对象对阻塞CS_Reader这一过程实现互斥。
2.主要数据结构int readCount:访问资源的读者线程数目;int writeCount:访问资源的写者线程数目;CRITICAL_SECTION RP_Writer:临界区对象,读者优先中用于阻塞写者;CRITICAL_SECTION CS_Writer:临界区对象,写者优先中实现写写互斥;CRITICAL_SECTION CS_Reader:临界区对象,写者优先中用于阻塞读者,体现写者优先struct Thread :线程信息结构体结构表示,成员变量包括int Number , char Type ,double RunTime, WaitTime ,分别代表线程序号,线程种类(读者或写者),等待时间,作业时间。
HANDLE Mutex1:互斥信号量,用于实现写者优先。
HANDLE Mutex2:互斥信号量,用于维护read_Count 修改。
HANDLE Mutex3:互斥信号量,用于维护write_Count 修改。
3. 主要代码结构int main() \\main 函数菜单界面 void ReaderPriority(char *file) \\读者优先主控程序 void RP_ReaderThread(void *p) \\读者优先-读者线程 void RP_WriterThread(void *p) \\读者优先-写者线程 void WriterPriority(char *file) \\写者优先主控程序 void WP_ReaderThread(void *p) \\写者优先-读者线程 void WP_WriterThread(void *p) \\写者优先-写者线程4. 主要代码段分析a) 创建文件输入流inFile 读入文件int main()RP_ReaderThread RP_WriterThread WP_ReaderThread WP_WriterThreadReaderPriority WritePriority2.读者优先读者线程部分:WaitForMutex = WaitForSingleObject(Mutex, -1);// P(h_mutex)readCount++;if(readCount == 1)// 读者线程进入临界区,实现读者优先{EnterCriticalSection(&RP_Writer);}ReleaseMutex(Mutex);// V(h_mutex)printf("Reader thread %d begins to read file.\n",Number);// 读者线程开始作业Sleep(RunTime);// 作业时间printf("Reader thread %d finished reading file.\n",Number);// 作业完成WaitForMutex=WaitForSingleObject(Mutex,-1);// P(h_mutex) 读者线程对象已触发readCount--;// 读者线程退出if(readCount == 0)// 所有读者线程都已作业完毕,释放临界区对象,写者可作业{LeaveCriticalSection(&RP_Writer);}ReleaseMutex(Mutex);// V(h_mutex)3.写者优先写者线程部分:printf ("Writer thread %d sents the reading require.\n", Number);// 读者线程从创建m_delay秒后,发送读申请WaitForMutex3 = WaitForSingleObject(Mutex3, -1);// P(Mutex3) 维护writeCount修改// P(h_mutex)writeCount++;if(writeCount == 1)// 临界区有写者线程作业时,阻塞一切读者线程{EnterCriticalSection(&CS_Reader);}ReleaseMutex(Mutex3);// V(Mutex3)EnterCriticalSection(&CS_Writer);// 写写互斥printf("Writer thread %d begin to write the file.\n",Number);Sleep(RunTime);printf("writer thread %d finishing writing file.\n",Number);LeaveCriticalSection(&CS_Writer);WaitForMutex3 = WaitForSingleObject(Mutex3,-1);// 维护writeCount修改writeCount--;if(writeCount==0)// 当所有写者线程作业完毕,释放读者线程临界区对象{LeaveCriticalSection(&CS_Reader);}ReleaseMutex(Mutex3);// V(Mutex3)三、实验结果1.基本数据基本数据:TestData.dat(见附件)数据文件包括n行测试数据,分别描述创建的n个线程是读者还是写者,以及读写操作的开始时间和持续时间。
每行测试数据包括四个字段,各个字段间用空格分隔。
第一字段为一个正整数,表示线程序号。
第二字段表示相应线程角色,R表示读者,w表示写者。
第三字段为一个正数,表示读写操作的开始时间:线程创建后,延迟相应时间(单位为秒)后发出对共享资源的读写申请。
第四字段为一个正数,表示读写操作的持续时间。
当线程读写申请成功后,开始对共享资源的读写操作,该操作持续相应时间后结束,并释放共享资源。
数据文件内容:1 R 3 52 W 4 53 R 5 24 R 6 55 W 5.1 32.源代码行数:代码共303行。
3.完成实验投入时间:累计共7小时4.讨论次数:3次5.测试数据分析:分析详情见1.基本数据6.测试结果分析:程序菜单界面:1)读者优先:读者优先结果分析:根据测试数据及读者优先原则可知,线程1R在第3s先执行,当它执行1s后,线程2W发出申请,但被阻塞,实现读写互斥。
然后线程3R,线程4R在第5、6s时发出申请并被准许访问数据区,实现了多个读者同时读数据允许。
而在5.1s发出写申请的线程5W则被阻塞。
当读者线程根据时间都完成后,写者线程2W先被唤醒,并且在它完成之前,写者线程5W仍然是阻塞状态,从而实现了写写互斥。
2)写者分析:写者优先结果分析:根据测试数据及写者优先原则可知,线程1R在第3s先执行,当它执行1s后,线程2W发出申请,但被阻塞,实现读写互斥。
然后线程3R、线程5W、线程4R在第5s、5.1s、6s时发出申请,均被阻塞。