1. 程式人生 > >nachos 增加全域性執行緒管理機制,控制執行緒數

nachos 增加全域性執行緒管理機制,控制執行緒數

這個問題看起來很簡單,卻還是花了我很多時間來解決。開始時候不能在.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,建立程序失敗。