Plainly LUA's co-process (Coroutine)

Source: Internet
Author: User
Tags lua
The threads in the process and multithreading are similar: have their own stacks, their own local variables, have their own instruction pointers, but share global variables and other information with other collaborators. The main difference between a thread and a coprocessor is that, in a multiprocessor case, multithreading is conceptually running multiple threads at the same time, and the co-process is done through collaboration, with only one thread running at any time. And this will only be suspended if the running process is explicitly required to be suspended.
You can use Coroutine.create to create a process: CO = coroutine.create (function () print ("HI") end)
There are three states of association: Hang, Run, stop. is suspended after creation, that is, does not run automatically. The status function can view the current state. The real strength of the process is that he can suspend a running piece of code through the yield function.
LUA's Resume-yield can exchange data with each other. If there is no yield, the extra parameters passed to the resume are passed as parameters to the main function of the master:
CO = coroutine.create (function (A, B, c) print ("Co", A, B, c) end) Coroutine.resume (CO, 1, 2, 3)
If there is no error, resume will return true and yield parameters: Co = coroutine.create (function (A, B) Coroutine.yield (A+b, A-a) end) print (coroutine . Resume (Co, 3, 8))
In the same way, yield returns the arguments passed by the corresponding resume: CO = coroutine.create (function ()
Print ("Co", Coroutine.yield ())
End
Coroutine.resume (CO)
Coroutine.resume (Co, 4, 5)
Finally, the return value of the Master function is the return value of the resume that corresponds to it (the first argument is true). CO = coroutine.create (function ()
Return 6, 7
End
Print (Coroutine.resume (CO))
Finish

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.