2012年1月10日 星期二

Unity Threading



在Unity上使用多執行緒主要有兩種方法。第一是在程式一開始執行時即丟出執行緒,在執行緒中以無窮迴圈的方式監聽或是接收運算結果。第二,在觸發時事件時才丟出執行緒。兩者的寫法分敘如下。

第一:無窮迴圈法
using System.Threading;
Thread m_thread;
void Start()
{
m_thread= new Thread(new ThreadStart(RunThread));
m_thread.Start();
}
void RunThread()
{
try {
      while(true){
      Computing();
 }catch(Exception e){
            Debug.Log(“Exception : “+e.ToString());
            OnApplicationQuit();
 }
}
void OnApplicationQuit()
{
m_thread.Abort();
}
void Computing()
{
for(int i=0;i<100000;i++) Mathf.Sqrt((float)i);
}
在這個案例中,由於迴圈做完數值運算結束就完成,即便是網路的監聽也沒有太大問題。但如果牽涉到GameObject的使用,便會警告 “can only be called from the main thread” error.而無解。請見討論, 經過測試跟Mutex沒有關係,錯誤仍會產生。
第二:觸發型
Using System.Threading
void Start()
{}
void Update()
{
if(IsThread)
{  Thread m_thread = new Thread(new ThreadStart(Computing));
   m_thread.Start();
}
}
void Computing()
{
for(int i=0;i<100000;i++) Mathf.Sqrt((float)i);
}
目前使用 unity的版本是3.4,在多執行緒量到一定程度時便會出現fatal error in gc


這個做法的相關問題在此有詳細的討論

最後,一位大神出現,說這問題在3.5版會獲得解決,他的名字叫做Joachim Ante, 來頭不小,是unity的CTO。就讓我們是目以待吧!

沒有留言:

張貼留言