Coroutine
A synergistic program is similar to a thread, which is an execution sequence that has its own stack, local variables, and instruction pointers, while sharing global variables and most other things with other co-programs. The main difference between a thread and a co-worker is that a multithreaded program can run several threads at the same time, and the co-program needs to work cooperatively. That is, a program with multiple co-programs can run only one co-program at any time, and the running co-program will only be paused when its display is suspended.
Principle Analysis
- The so-called "threads" created by Coroutine are not real operating system threads, but are actually simulated by saving the stack state.
- Because it is a fake thread, the overhead of switching threads is minimal, and the creation of threads is lightweight, and new_thread just creates a new stack of stacks for storing new coroutine in memory, also known as Lua_state
- Call yield () the current thread is handing over control, and can also return parameters through the stack. The thread that calls resume (which can be understood as the main thread) obtains the parameters returned.
- Lua yield () is somewhat similar to Thread.yield () in Java, but the difference is greater. After the yield call in Java only switches the current CPU to another thread, the CPU may continue to return to thread execution at any time.
- I prefer to compare the yield () and resume () in Lua with the Wait () and notify () in Java. They behave in a basic and consistent form.
Why Coroutine?
Coroutine has a basic understanding of the above, so everyone will like me to think, why use Coroutine? First study the advantages
- Each coroutine has its own private stack and local variables.
- At the same time, only one coroutine is executing without locking the global variable.
- Sequential control, complete sequence of program execution. When the usual multithreading is started, the timing of its operation is unpredictable, which often makes it difficult to test all the situations. Therefore, the use of coroutine to solve the situation should give priority to using Coroutine.
U3d's spaceship Space shooting example, using Coroutine