山大操作系统课程设计报告(全套) 下载本文

内容发布更新时间 : 2024/5/14 4:06:10星期一 下面是文章的全部内容请认真阅读。

计算机科学与技术学院实验报告:3

实验题目:信号量同步问题 日期:2010-11-10 姓名: 实验目的: 在本次实验中,通过使用信号量,在原有的程序框架的基础上添加关键代码实现生产者/消费者同步问题。从而深入理解Nachos的信号量的使用以及实现,生产者/消费者问题是如何用信号量实现的以及 在Nachos中是如何创建线程,实现多线程。 硬件环境: 软件环境: Linux 实验步骤: 1.首先初始化三个信号量,代码如下: mutex = new Semaphore(\信号量初始化为1,才能起到加锁功能 nfull = new Semaphore(\的大小在生产者没生产前为0 nempty = new Semaphore(\的大小应该为buffer的大小 2.首先考虑生产者进程,首先要查看buffer是否有空, nempty->P();if nempty>0,nempty=nempty -1,当对缓冲区操作时必须要加锁:mutex->P();加锁. 然后向ring中放入message信息,其次还要解锁mutex->V();解锁.最后通知消费者buffer有新信息, nfull->V();nfull=nfull+1;具体实现代码如下: 3. 考虑消费者进程,像生产者进程一样,查看buffer中是否有信息 nfull->P();if nfull>0,nfull-1;取消息时也要上锁,即:mutex->P();加锁. 然后从ring buffer中取出信息;其次mutex->V();解锁;最后通知生产者bufferr有空nempty->V();nempty=nempty+1,具体代码如下: 4. 创建线程生成一个生产者的代码: producers[i] = new Thread(prod_names[i]); producers[i] -> Fork(Producer,i); 4. 创建线程生成一个消费者的代码: producers[i] = new Thread(prod_names[i]); producers[i] -> Fork(Producer,i); 关键代码: void Producer(_int which) { int num; slot *message = new slot(0,0); for (num = 0; num < N_MESSG ; num++) { //这是消息创建的代码 message->thread_id=which; message->value=num; //p,v 操作 nempty->P(); mutex->P(); ring->Put(message); //p,v 操作 mutex->V(); nfull->V(); } } void Consumer(_int which) { char str[MAXLEN]; char fname[LINELEN]; int fd; slot *message = new slot(0,0); sprintf(fname, \ // create a file. Note that this is a UNIX system call. if ( (fd = creat(fname, 0600) ) == -1) { for (; ; ) { // p,v,操作 nfull->P(); mutex->P(); perror(\Exit(1); } ring->Get(message); // p,v,操作 mutex->V(); nempty->V(); // form a string to record the message sprintf(str,\ message->thread_id, message->value); //把信息写入文件 if ( write(fd, str, strlen(str)) == -1 ) { } //---------------------------------------------------------------------- // ProdCons // 初始化信号量以及需要的生产者消费者线程 //---------------------------------------------------------------------- void ProdCons() { int i; DEBUG('t', \ // 初始化信号量,包括一个访问互斥信号量,初值为1; //一个nempty信号量,初值为缓冲区的大小 //一个nfull的信号量,初值为0 mutex=new Semaphore(\ nempty=new Semaphore(\ nfull=new Semaphore(\ // 新建一个缓冲区 ring=new Ring(BUFF_SIZE+1); perror(\ Exit(1); } }