Cooperative program Coroutine in LUA

Source: Internet
Author: User

In Lua, the covariance and multithreading are very similar, each process has its own stack, its own local variables, can be implemented by Yield-resume in the transition between the co-process. The difference is that theLUA process is non-preemptive multithreading and must be manually switched between different threads, and only one co-process can run at the same time. And the process in LUA cannot be externally stopped, and may cause the program to block.

Collaboration Program (Coroutine):

Three states:suspended(hangs, co-creation completed or after yield),running(run),dead(the state after the function is gone, this time can no longer resume).

Coroutine.create (ARG): Creates a synergistic program based on a function with the parameter as a function

Coroutine.resume (CO): Make the collaboration from suspend to run (1) Activate Coroutine, that is, let the co-function start to run, (2) wake yield, so that the pending synergy continues to run the last place. The function can pass in a parameter

Coroutine.status (CO): View collaboration status

Coroutine.yield (): Enables a running collaboration to be suspended and can pass in parameters

The two purposes of the resume function are to make the collaboration hang, but there is a slight difference, see the following example:

Coroutinefunc = function (A, b)     for i = 1, ten do        print (I, A, b)        Coroutine.yield ()    Endendco2 = coroutine.cr Eate (Coroutinefunc)-        -Creating a synergistic program Co2coroutine.resume (CO2, max)                --1 100 200 Open Synergy, incoming parameters are used to initialize Coroutine.resume ( CO2)-                        -2 coroutine.resume (CO2, Max, max)                --3 100 200 continue collaboration, invalid incoming parameter CO3 = coroutine.create (coroutinefunc) 
   --Creating a Synergistic program Co3coroutine.resume (CO3, 1, max)                --300 400 open synergy, incoming parameters for initializing Coroutine.resume (CO3)                        --2 300 400 Coroutine.resume (CO3)                        

The power of collaboration in Lua is also the ability to Exchange data through Resume-yield:

(1) Resume passes the parameter to the program (equivalent to the function parameter call);

(2) The data is passed from yield to resume;

(3) The parameters of resume are passed to yield;

(4) The return value at the end of the collaboration code is also passed to the resume

The parameter transfer in synergy is very flexible, we must pay attention to distinguish, in the start Coroutine, resume parameters are passed to the main program, when the yield is awakened, the parameters are passed to yield. look at the following example:

CO = coroutine.create (function (A, b) print ("Co", A, B, Coroutine.yield ()) end) Coroutine.resume (CO, 1, 2)        -No output, note two The numeric parameters are passed to the function Coroutine.resume (CO, 3, 4, 5)        --co 1 2 3 4 5, where two numeric parameters are passed to yield by resume 

Lua's synergy is called Asymmetric Synergy (asymmetric coroutines), which means "suspending an executing synergistic function" and "making a function that is suspended for co-execution again" is different, and some languages provide symmetric collaboration ( symmetric coroutines), which is responsible for "state switching between execution and suspend" using the same function.

Note: Theresume runs in protected mode , so if there is an error inside the co-program,Lua does not throw an error, but instead returns the error to the resume function.

Here is a bit of my personal understanding:

(1) Resume can be understood as a function call, and can pass in parameters, activation association at the same time, the parameters are passed to the program, wake yield, parameters are passed to yield;

(2) yield is equivalent to a special return statement, except that it is only a temporary return (hang), and yield can be returned with a return parameter, which is passed to the resume.

To understand the meaning of the above two sentences, let's take a look at how to use Coroutine to solve the simple implementation of producer-consumer problems:

Producefunc = function ()    while true does        local value = Io.read ()        print ("Produce:", value)        Coroutine.yield (value)        --Returns the value of the production    Endendconsumer = function (p)    while true does        local status, Value = Coroutine.resume (p);        --Awaken the producer to produce        print ("Consume:", value)    endend--consumer-driven design, that is, the consumer needs the product to find the producer request, the producer completes the production to provide the consumer producer Coroutine.create (Producefunc) consumer (producer)

This is a consumer-driven design, and we can see that the result of a resume operation is to wait for a yield return, which is much like a normal function call, with a wood. We can also add an intermediate processing link between production and consumption (filter):

Producefunc = function ()    while true does        local value = Io.read ()        print ("Produce:", value)        Coroutine.yield (value)        --Returns the value of the production    endendfiltefunc = function (p)    while true does        local status, Value = Coroutine.resume (p);        Value = value *100            --magnification 100 times times        Coroutine.yield (value)    Endendconsumer = function (f, p) while    true        local status, value = Coroutine.resume (f, p);        --Awaken the producer to produce        print ("Consume:", value)    endend--consumer-driven design, that is, the consumer needs the product to find the producer request, the producer completes the production to provide the consumer producer Coroutine.create (producefunc) filter = Coroutine.create (filtefunc) consumer (filter, producer)

As you can see, we magnify the produced values by 100 times times in the median filter.

This example should make it easy to understand how Coroutine uses Resume-yield for value passing, like "Call Function-return value", which means that the resume is used like a function call , Yield is used just like a return statement . The flexibility of coroutine is also reflected in this pass through the Resume-yield value.

Http://www.cnblogs.com/sifenkesi/p/3824321.html

Co-Program Coroutine (RPM) in Lua

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.