Parsing Lua collaboration program

Source: Internet
Author: User

AboutLua collaboration programIs the content to be introduced in this article, mainly to learnLuaMediumThreadFor more information about the system program, see the details.

1. What is coroutine )?

Collaboration Program(Coroutine) andThreadIt is similar: it has an independent stack, independent local variables, and independent command pointers, but shares a lot of information such as global variables with other coders.

ThreadAndCollaborationThe main difference between a program is that, in the case of a multi-processor, a multi-threaded program runs multiple threads at the same time, while a collaborative program is done through collaboration, at any specified time, only one program is running, and this program is suspended only when it is explicitly required to be suspended. The collaboration program is a bit similar to synchronous multithreading, and several threads waiting for the same thread lock are a bit similar to collaboration.

What is the difference between collaboration and sequential execution? At any given time point, only one coordinator can be run. What is the difference between this and sequential execution? The key lies in the yield function. If it takes cpu time or waits for a resource in sequence, the program will be stuck in this place and cannot move forward. The emergence of a collaboration program is to allow the threads waiting for resources to let out the resources and perform operations on the next collaboration program. Yield can be suspended when an error occurs and resumed the next time.

2. Several statuses of collaboration

Pending state: When a collaborative program is created, the initial state is suspended. The coroutine. yield function changes the program from running state to suspended state.

Running State: The coroutine. resume function enables the program to change from suspended state to running state.

Stop State: the collaboration program ends and enters the stop state.

3. coroutine. resume

Resume can pass parameters to the coprocessor and resume the suspended program to the running state.

 
 
  1. coroutinecoroutine.co = coroutine.create(function (a,b,c)  
  2.     print("co", a, b, c)  
  3. end)  
  4. coroutine.resume(co, 1, 2, 3) --> co 1 2 3resume 

Coroutine. resumeThreadReturns the result when it ends or encounters coroutine. yield.

1) coroutine. resume parameters:ThreadWhen the function is run for the first time, the parameter is used as the thread function parameter. If yield does not explicitly return the parameter, the parameter of coroutine. resume is returned as an additional parameter of yield.

2) If the thread is suspended (or suspended at the beginning), true is returned when the resume function continues to run. If the thread has stopped or encounters other errors, the resume function returns false and error messages.

3) when the thread ends, the return value of the main function of the thread is used as the additional return value of coroutine. resume.

This feature is very subtle. It can be seen that coroutine. resume is actually a blocking function, blocking waits for the coprocessor to complete or yield to exit. You can regard the coprocessor as a waiting object. coroutine. resume will return if the object is waiting for return. This feature is important to remember when calling coroutine. resume to block the call thread!

4. coroutine. yield

Yield can return additional parameters or suspend the coprocessor

 
 
  1. co = coroutine.create(function (a,b)  
  2.     coroutine.yield(a + b, a - b)  
  3. end)  
  4. print(coroutine.resume(co, 20, 10)) --> true 30 10  
  5.  
  6. co = coroutine.create (function ()  
  7.     print("co", coroutine.yield())  
  8. end)  
  9. coroutine.resume(co)  
  10. coroutine.resume(co, 4, 5) --> co 4 5 

The yield function can suspend the program and return the status to resume. When we activate the suspended program, yield returns (here the return is from the blocking status) run the program until yield or the program ends again.

5. symmetric and asymmetric synergy

Symmetric collaboration: The functions for status transition between execution and suspension are the same.

Asymmetric synergy: the function that suspends an ongoing collaboration is different from the function that re-executes a suspended collaboration (resum and yield)
 
6. consumer-driven producer-consumer model

When a consumer needs a value, he calls the producer production value. After the producer produces the value, it stops until the consumer requests again. We call this design a consumer-driven design. The common producer-consumer model is a product-driven design. Producers continuously produce products. consumers use critical zones to protect product consumption.

Collaboration provides an ideal solution to this problem, because the resume-yield relationship between the caller and the called is constantly reversed. When a collaborative call to yield does not enter a new function, instead, it returns a pending call to resume. Similarly, when calling resume, instead of starting a new function, yield is returned. This is exactly what we need. It is consistent with the way in which send-receive works collaboratively: receive wakes up the producer to produce a new value, and send sends the generated value to the consumer for consumption.

 
 
  1. function receive (prod)  
  2.     local status, value = coroutine.resume(prod)  
  3.     return value  
  4. end  
  5.  
  6. function send (x)  
  7.     coroutine.yield(x)  
  8. end  
  9.  
  10. function producer ()  
  11.     return coroutine.create(function ()  
  12.         while true do  
  13.             local x = io.read() -- produce new value  
  14.             send(x)  
  15.         end  
  16.  
  17.     end)  
  18. end  
  19.  
  20. function filter (prod)  
  21.     return coroutine.create(function ()  
  22.         local line = 1 
  23.         while true do  
  24.             local x = receive(prod) -- get new value  
  25.             x = string.format("%5d %s", line, x)  
  26.             send(x) -- send it to consumer  
  27.             lineline = line + 1  
  28.         end  
  29.     end)  
  30. end  
  31.  
  32. coroutine.resumefunction consumer (filter)  
  33.     while true do  
  34.         local x = receive(filter) -- get new value  
  35.         io.write(x, "\n") -- consume new value  
  36.     end  
  37. end  
  38. p = producer()  
  39. f = filter(p)  
  40. consumer(f) 

After reading the above example, you may naturally think of UNIX pipelines. Collaboration is a non-preemptible Multi-ChannelThread. In pipeline mode, each task runs in an independent process, while in collaboration mode, each task runs in an independent collaborative code. The pipeline reads consumer) and writes producer) to provide a buffer, so there is no limit on the speed of the two, which is very important in the context pipeline, because switching between processes is costly.CollaborationIn this mode, the switching between tasks is relatively low, which is equivalent to function calls. Therefore, read/write can be performed collaboratively.

Summary: AboutLua collaborationThe content of the program has been introduced. I hope this article will help you!

Related Article

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.