Coroutine is not a real multi-threaded

Source: Internet
Author: User

From: http://www.zhihu.com/question/23895384

Speaking of Coroutine, we have to mention two things that are farther away. At the operating system (OS) level, there are processes (process) and threads (thread) Two (only from our common speaking) the actual "thing" (not to say the concept is because these two guys are really not just concepts, but actually exist, the resources of the OS's code management). These two things are used to simulate "parallel", write operating system programmers by using a certain strategy to different processes and threads to allocate CPU computing resources, so that users "think" a few different things at the same time "." On a single CPU, it is the OS code that forces a process or thread to be suspended, replaced by another, so that it is actually serial, just "conceptually parallel." On multicore CPUs today, threads can be "really parallel."

Coroutine, translated into "co-process", the initial encounter with the two concepts are immediately linked. First of all, Coroutine is the compiler level, process and thread are operating system level. The implementation of Coroutine is usually a corresponding proposal for a language, which is then passed into the compiler standard and then the compiler vendor implements the mechanism. Process and thread seem to be at the language level, but the endogenous principle is that the operating system first has this thing, and then exposed to the user through a certain API, the two are different here. Process and thread are the OS through the scheduling algorithm, save the current context, and then from the last pause where the calculation starts again, where the restart is not expected, each time the CPU calculates the number of instructions and the code ran over the CPU time is related, Running to the OS allocated CPU time will be forced to suspend by the OS when it arrives. Coroutine is the magic of the compiler, by inserting the relevant code to enable the code snippet to achieve segmented execution, the place to start is the yield keyword specified, once will run to a yield corresponding to the place.

for Coroutine, the following is an implemented function, in which fragments are divided into 2 segments by the yield keyword:

IEnumerator YieldSomeStuff(){    yield "hello"; Console.WriteLine("foo!"); yield "world";}


Propulsion code (analog, non-Actual):

IEnumerator e = YieldSomeStuff();while(e.MoveNext()){    Console.WriteLine(e.Current);}


to advance the staging of the entire code fragment. More detailed analysis is mentioned in the article as  @ Michael Dunne. As long as the explanation is, for coroutine, is the compiler help do a lot of things to make the code is not a one-time run to the end, rather than the operating system forced to suspend. How much code runs each time is predictable . However, process and thread are completely different at this level, and these two things are managed by the operating system. In unity, the Startcoroutine method is a propeller. The Startcoroutine initiates a while loop similar to the above. Because it is a while loop, coroutine itself is not actually "asynchronous".

Coroutine The location of the entire unity system, the following diagram illustrates:

Note: Images from the coroutines++

Unity Official document also reads "Normal Coroutine the word "after Update", the following is the first line:

Normal coroutine updates are run after the Update function returns. A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes. Different uses of Coroutines:yield; The coroutine will continue after all Update functions have been called on the next frame.yield WaitForSeconds(2); Continue after a specified time delay, after all Update functions have been called for the frameyield WaitForFixedUpdate(); Continue after all FixedUpdate has been called on all scriptsyield WWW Continue after a WWW download has completed.yield StartCoroutine(MyFunc); Chains the coroutine, and will wait for the MyFunc coroutine to complete first.


By the above figure and the text can be roughly guessed that. NET virtual machines in each frame loop, they go to each compiler predefined portal. For Coroutine, the compiler needs to generate some code, and in each cycle, Unity's update () returns, guaranteeing that the code after yield is called correctly, thus forming a mechanism that we see as a function fragment execution.

The process is not really multi-threaded, the following code in the process to join the dead loop, the operation is stuck.

usingUnityengine;usingSystem.Collections; Public classWwwtest:monobehaviour { Public stringURL ="http://images.earthcam.com/ec_metros/ourcams/fridays.jpg"; Privatewww www;  PublicUILabel label; Private UINTAdd =0; voidStart () {Startcoroutine (DownLoad ());        Startcoroutine (ADD ()); Add=0; }        //Update is called once per frame    voidUpdate () {Label.text=Add.    ToString (); } IEnumerator DownLoad () {yield return NULL; Debug.Log ("Start 1"); yield return NewWaitforseconds (5); Debug.Log ("1"); www=NewWWW (URL); Debug.Log ("www start"); yield returnwww; Getcomponent<GUITexture> (). Texture =www.texture; Debug.Log ("www done"); } IEnumerator Add () { while(true) ; yield return NULL; }}

Coroutine is not a real multi-threaded

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.