1. 程式人生 > >Unity 協程與執行緒區別

Unity 協程與執行緒區別

1、協程 不是 執行緒,協同程式是 不同步 

      一個執行緒在程式中和其他執行緒是非同步執行的,在多處理器機器中一個執行緒可以同時與所有其他執行緒的實時執行其程式碼,這使得執行緒程式設計能夠解決很複雜的事情,因為可能在相同的時間裡一個執行緒在改變它而另一個執行緒正在讀取它,這意味著另一個執行緒實際上可以改變的東西在遊戲中處理的中間似乎是你的原始碼一行。這是因為你寫的程式碼是由機器變成組合語言,更是更復雜。正因為如此,你必須通過鎖,以確保這種情況不會由任何確保沒有共享記憶體發生。或者通過鎖定其他執行緒使用同一塊記憶體,當他們在讀取或更改時。

2、什麼是協程?

      協同程式絕對不是一個執行緒。這意味著在同一時間只有一個協同程式在執行,它會被執行在遊戲的主執行緒上,所以實際上在同一時間遊戲的核心只有一個協同程式在執行[這段翻譯的不太好]

     你永遠不需要擔心同步或鎖定一個值當你正在編寫一個協同程式。你有完全的控制權,直到你的程式碼執行到 yiedld

  因此總結一下協程的定義

    協程只是部分執行,並假定在適當的條件得到滿足,在未來的某一時刻將被恢復,直到它的工作完成

Unity processes coroutines every frame of the game for every object that has one or more running.  The processing occurs after Update and before LateUpdate for most yield statements, but there are special cases:

Unity的流程協同程式在遊戲的每一幀每個物件為具有一個或多個正在執行的。Update() 之後,LateUpdate()之前 ,發生的 yield 語句的處理,但也有特殊情況


當協程被啟用,它會一直到下一個 yield語句執行,然後它會暫停,直到它恢復。你可以在上圖中看到它會恢復,根據你的 yield語句

讓我們來看看一個非常簡單的協程

IEnumerator TestCoroutine(){ 
while(true)  
{           
Debug.Log(Time.time);           
yield return null;      
}
}

該協程將會永遠執行下去。它記錄當前的時間,然後yield,當它被恢復,它又進入了這個迴圈,記錄一次時間,遇到 yield 並重復之前的操作

The code inside the loop is exactly like an Update function.  It runs once every frame for this object, just after the script's Update routine runs (if it has one).

這程式碼迴圈就像 Update() 函式。這個物件在每一幀中執行,指令碼的Update 程式執行後(如果有的話)

When you call StartCoroutine(TestCoroutine()) the code executes immediately up to the first time it yields, it will then be resumed when Unity processes coroutines for this object.

當你呼叫 StartCoroutine(TestCoroutine()) 程式碼立即第一次得到執行 然後 yield,當Unity 引擎再次處理這個GameObject時,協程會被恢復

If you start a coroutine early in the processing of a game object, like creating one in Start, Update or OnCollisionEnter then that coroutine will immediately run up to the first yield, then it will resume during the same frame if you yield return null .

如果你在早於Unity處理到GameObject就執行一個協程 比如 Start(),Update()或OnCollisionEnter()將會繼續執行,當第一次遇到yield,然後同一幀會恢復,如果你yield null。有時候會有奇怪的結果,如果你不考慮它。