Nachos pro1.1 join()方法修改

本文基本java版的nachos系统进行学习及修改。

join函数的作用即为等待调用此函数线程运行完毕。当前线程A调用另一个线程(处于就绪状态) B的join函数时,即A执行B.join()时 (A和B在Nachos中均为KThread类型对象), A被挂起, 直到B运行结束后, join函数返回, A才能继续运行。如果这个线程已经结束,马上返回。且join()函数只能被调用一次,第二次调用不能保证返回,且调用join()函数的线程必须不能是当前线程。join()函数结束时唤醒在等待队列中的所有线程,因此需要实现join()方法和修改finish()方法。

首先,在类体声明一个等待队列waitQueue.

private static ThreadQueue waitQueue = null;
int join_counter = 0;

修改join方法:

public void join() {
		Lib.debug(dbgThread, "Joining to thread: " + toString());
		// 确认调用此方法的线程是不是currenThread,如果是,接着往下执行
		Lib.assertTrue(this != currentThread);
		Lib.assertTrue(join_counter == 0);
		
		//关中断;获取当前线程的状态
		boolean intStatus  = Machine.interrupt().disable();
		if(status!=statusFinished){
			//将当前运行中的线程加到阻塞队列中
			waitQueue.waitForAccess(currentThread);
			//当前线程睡眠,放弃占用CPU
			sleep();
		}
		//保存当前的状态,等到中断结束回到当前线程时可以接下去执行
		Machine.interrupt().restore(intStatus);
	}
修改finish方法:

public static void finish() {
		Lib.debug(dbgThread, "Finishing thread: " + currentThread.toString());
		//关中断
		Machine.interrupt().disable();
		//当前线程结束的标志
		Machine.autoGrader().finishingCurrentThread();
		
		Lib.assertTrue(toBeDestroyed == null);
		//表示当前线程即将被销毁
		toBeDestroyed = currentThread;
		//修改当前线程的状态为结束
		currentThread.status = statusFinished;
		//调用阻塞(等待)队列中的第一个线程准备执行
		KThread waitThread = currentThread.waitQueue.nextThread();
		if (waitThread != null)
			waitThread.ready();
		//当前线程放弃对CPU的占有
		sleep();

	}


接下来,测试我们修改的是否正确:

①模仿PingTest新建一个JoinTest内部类
private static class JoinTest implements Runnable {

		public void run() {
			System.out.println("B线程运行中");
			System.out.println("B线程结束运行");
		}

	}
②新建joinTest方法

/**
	 * join方法测试
	 */
	public static void joinTest(){
		System.out.println("\n任务phase1.1");
		Lib.debug(dbgThread, "开始join方法测试");
		KThread aThread = new KThread(new JoinTest());
		aThread.setName("新线程").fork();
		System.out.println("A线程运行中");
		System.out.println("A线程暂停");
		aThread.join();
		System.out.println("A线程恢复运行");
	}

最后,在ThreadKernel类的selfTest方法里调用joinTest方法:

public void selfTest() {
		KThread.selfTest();
		KThread.joinTest();
		Semaphore.selfTest();
		SynchList.selfTest();
		if (Machine.bank() != null) {
			ElevatorBank.selfTest();
		}
	}


运行,我们看到了如下的结果:



测试成功!

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值