nachos 增加全局线程管理机制,控制线程数

来源:互联网 发布:淘宝女式小脚裤 编辑:程序博客网 时间:2024/05/16 10:32
这个问题看起来很简单,却还是花了我很多时间来解决。开始时候不能在.cc文件中实现.h文件中的私有方法,后来不知道怎么又不报错了,很困惑。开始老想在调用构造函数的时候判断threadnum<THREAD_MAX,再进行thread的创建,后来发现这个方法根本不好用,在构造函数里做判断,本来就不合理。
最后在小新的指导下,在thread中创建一个静态方法 getInstance,然后在其中判断师傅符合条件,如果符合则返回一个new thread,否则返回NULL。然后将构造方法声明为private,禁止外部调用,只能通过getInstance获得thread的实例。

1.在system.h和system.cc中声明和初始化threadnum ,用来记录当前线程数。
system.h:
extern int threadnum;
system.cc
threadnum = 0;

2.修改thread.h文件,将构造函数声明为私有,并声明一个新的静态方法getInstance.
private:
    Thread(char* debugName);
public:
    static Thread* getInstance(char* debugName);  

3.在thread.cc中实现getInstance方法,修改构造函数和析构函数
在构造函数中添加一行 ++threadnum;
在析构函数中添加一行 --threadnum;

//Thread::getInstance
//created to control the num of threads
Thread*
Thread::getInstance(char* threadName)
{
//当线程数小于最大值时,创建线程
 if(threadnum < THREAD_MAX)
    return new Thread(threadName);
//否则,返回空
else
  {
    DEBUG('s',"You can not create more threads.\n");
    return NULL;    
   }
}

4.测试,修改测试文件,将原来的new 方法修改为getInstance,并在调用fork前判断
void
ThreadTest1(int num)
{
    DEBUG('t', "Entering ThreadTest1");
  for(int i = 0 ; i< num; ++i)
 {
 Thread *t = Thread::getInstance("forked thread");    //声明一个新线程
 if( t!= NULL)
     t->Fork(SimpleThread);
  }

    SimpleThread(currentThread->getTid());                
 }

重新make,执行命令 ./nachos -q 130

可以看到结果中只生成了128个线程,当循环到129次时,返回NULL,创建进程失败。



原创粉丝点击