Unity 协程与线程区别

来源:互联网 发布:fs forse.js 编辑:程序博客网 时间:2024/06/07 12:29

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。有时候会有奇怪的结果,如果你不考虑它。


0 0
原创粉丝点击