Lua Coroutine(coroutine)
What is a coroutine?
Lua coroutines are similar to threads: they have independent stacks, independent local variables, and independent instruction pointers, while sharing global variables and most other things with other coroutines.
A coroutine can be understood as a special kind of thread that can pause and resume its execution, thereby allowing non-preemptive multitasking.
Coroutines are a very powerful feature, but they are also complex to use.
Basic Syntax
Coroutines are supported by the coroutine module.
With coroutines, you can use coroutine.create in a function to create a new coroutine object, and use coroutine.resume to start its execution. A coroutine can call coroutine.yield to actively pause its own execution and return control to the caller.
| Method | Description |
|---|---|
| coroutine.create() | Create a coroutine and return it; the parameter is a function, which when used together with resume wakes up the function call |
| coroutine.resume() | Restart a coroutine, used together with create |
| coroutine.yield() | Suspend a coroutine, setting it to the suspended state; this used together with resume can have many useful effects |
| coroutine.status() | Check the status of a coroutine |
| Note: a coroutine has three states: dead, suspended, running; for when these states occur, please refer to the following program | |
| coroutine.wrap() | Create a coroutine and return a function; once you call this function, you enter the coroutine; this overlaps with create |
| coroutine.running() | Return the currently running coroutine; a coroutine is a thread, and when using running, it returns the thread number of a coroutine |
The following example demonstrates how to use Lua coroutines:
Example
function
foo
(
)
(
"Coroutine foo starts executing"
)
local
value
=
coroutine.yield
(
"Pause foo's execution"
)
(
"Coroutine foo resumes execution, the value passed in is: "
..
tostring
(
value
)
)
(
"Coroutine foo finishes executing"
)
end
-- create a coroutine
local
co
=
coroutine.create
(
foo
)
-- start the coroutine
local
status
,
result
=
coroutine.resume
(
co
)
(
result
)
-- output: pause foo's execution
-- resume the coroutine's execution and pass in a value
status
,
result
=
coroutine.resume
(
co
,
42
)
(
result
)
-- output: coroutine foo resumes execution, the value passed in is: 42
In the above example, we defined a function named foo as a coroutine. In the function, we used coroutine.yield to pause the coroutine's execution and return a value
. In the main program, we used coroutine.create to create a coroutine object and coroutine.resume to start its execution.
After the first call to coroutine.resume, the coroutine executes up to coroutine.yield and pauses, returning a value to the main program. Then we call coroutine.resume again and pass in a value as the parameter when the coroutine resumes.
The output of the code above is:
协同程序 foo 开始执行
暂停 foo 的执行
协同程序 foo 恢复执行,传入的值为: 42
协同程序 foo 结束执行
nil
It should be noted that the status of a coroutine can be obtained through the coroutine.status function; by checking the status, you can determine the execution state of the coroutine (such as running, suspended, dead, etc.).
The following example demonstrates the usage of the above methods:
coroutine_test.lua file
-- coroutine_test.lua file
-- created a new coroutine object co, in which the coroutine function prints the passed-in parameter i
co
=
coroutine.create
(
function
(
i
)
(
i
)
;
end
)
-- used coroutine.resume to start the execution of coroutine co, passing in parameter 1. The coroutine starts executing and prints 1
coroutine.resume
(
co
,
1
)
-- 1
-- checked the status of coroutine co through coroutine.status, output is dead, indicating the coroutine has finished executing
(
coroutine.status
(
co
)
)
-- dead
(
"----------"
)
-- used coroutine.wrap to create a coroutine wrapper, converting the coroutine function into a directly callable function object
co
=
coroutine.wrap
(
function
(
i
)
(
i
)
;
end
)
co
(
1
)
(
"----------"
)
-- created another coroutine object co2, in which the coroutine function prints numbers 1 to 10 through a loop, and when the loop reaches 3, outputs the current coroutine's status and the running thread
co2
=
coroutine.create
(
function
(
)
for
i
=
1
,
10
do
(
i
)
if
i
==
3
then
(
coroutine.status
(
co2
)
)
--running
(
coroutine
.
running
(
)
)
--thread:XXXXXX
end
coroutine.yield
(
)
end
end
)
-- continuously called coroutine.resume to start the execution of coroutine co2
coroutine.resume
(
co2
)
--1
coroutine.resume
(
co2
)
--2
coroutine.resume
(
co2
)
--3
-- checked the status of coroutine co2 through coroutine.status, output is suspended, indicating the coroutine is paused
(
coroutine.status
(
co2
)
)
-- suspended
(
coroutine
.
running
(
)
)
(
"----------"
)
The output of the above example is:
1
dead
----------
1
----------
1
2
3
running
thread: 0x7fb801c05868 false
suspended
thread: 0x7fb801c04c88 true
----------
coroutine.running shows that a coroutine is implemented as a thread at the lower level.
When you create a coroutine, an event is registered in a new thread.
When resume is used to trigger the event, the coroutine function created is executed; when yield is encountered, it means the current thread is suspended, waiting for resume to trigger the event again.
Next, let's analyze a more detailed example:
Example
function
foo
(
a
)
(
"foo function output"
,
a
)
return
coroutine.yield
(
2
a
)
-- return the value of 2*a
end
co
=
coroutine.create
(
function
(
a
,
b
)
(
"first coroutine execution output"
,
a
,
b
)
-- co-body 1 10
local
r
=
foo
(
a
1
)
(
"second coroutine execution output"
,
r
)
local
r
,
s
=
coroutine.yield
(
a
b
,
a
b
)
-- the values of a and b are passed in when the coroutine is called the first time
(
"third coroutine execution output"
,
r
,
s
)
return
b
,
"end coroutine"
-- the value of b is passed in when the coroutine is called the second time
end
)
(
"main"
,
coroutine.resume
(
co
,
1
,
10
)
)
-- true, 4
(
"--divider----"
)
(
"main"
,
coroutine.resume
(
co
,
"r"
)
)
-- true 11 -9
(
"---divider---"
)
(
"main"
,
coroutine.resume
(
co
,
"x"
,
"y"
)
)
-- true 10 end
(
"---divider---"
)
(
"main"
,
coroutine.resume
(
co
,
"x"
,
"y"
)
)
-- cannot resume dead coroutine
(
"---divider---"
)
The output of the above example is:
第一次协同程序执行输出 1 10
foo 函数输出 2
main true 4
--分割线----
第二次协同程序执行输出 r
main true 11 -9
---分割线---
第三次协同程序执行输出 x y
main true 10 结束协同程序
---分割线---
main false cannot resume dead coroutine
---分割线---
The above example is explained as follows:
- Call resume to wake up the coroutine; the resume operation returns true on success, otherwise returns false;
- The coroutine runs;
- It runs to the yield statement;
- yield suspends the coroutine, and the first resume returns; (Note: here yield returns, and the parameter is the parameter of resume)
- The second resume wakes up the coroutine again; (Note: in the parameters of resume here, except for the first parameter, the remaining parameters will be used as the parameters of yield)
- yield returns;
- The coroutine continues running;
- If you continue to call the resume method after the coroutine finishes running, the output is: cannot resume dead coroutine
The power of the combination of resume and yield lies in that resume is in the main program, which passes external state (data) into the coroutine; while yield returns internal state (data) to the main program.
Producer-consumer problem
Now we will use Lua's coroutines to solve the classic producer-consumer problem.
Example
local
newProductor
function
productor
(
)
local
i
=
0
while
true
do
i
=
i
1
send
(
i
)
-- send the produced items to the consumer
end
end
function
consumer
(
)
while
true
do
local
i
=
receive
(
)
-- get items from the producer
(
i
)
end
end
function
receive
(
)
local
status
,
value
=
coroutine.resume
(
newProductor
)
return
value
end
function
send
(
x
)
coroutine.yield
(
x
)
-- x represents the value to be sent; after the value is returned, the coroutine is suspended
end
-- start the program
newProductor
=
coroutine.create
(
productor
)
consumer
(
)
The output of the above example is:
1
2
3
4
5
6
7
8
9
10
11
12
13
……
Differences between threads and coroutines
The main difference between threads and coroutines is that a program with multiple threads can run several threads simultaneously, while coroutines need to cooperate with each other to run.
At any given moment only one coroutine is running, and this running coroutine is only suspended when it is explicitly asked to be suspended.
Coroutines are somewhat similar to synchronous multithreading; several threads waiting on the same thread lock are somewhat similar to coroutines.
The main differences are summarized as follows:
-
Scheduling: threads are usually preemptively scheduled by the operating system's scheduler, which switches execution rights between different threads. Coroutines, on the other hand, are non-preemptively scheduled, and the programmer explicitly controls the transfer of execution rights.
-
Concurrency: threads execute concurrently, with multiple threads running simultaneously on multiple processor cores, or switching execution on a single core through time-slicing. Coroutines are cooperative, with only one coroutine in the running state, and other coroutines must wait for the current coroutine to voluntarily give up execution rights.
-
Memory usage: threads usually require independent stacks and contexts, so creating and destroying threads brings extra overhead. Coroutines, however, can share the same stack and context, so the overhead of creating and destroying coroutines is smaller.
-
Data sharing: threads can share memory space, but attention must be paid to thread safety and synchronization issues. Coroutines usually share data through parameter passing and return values, and data isolation between different coroutines is better.
-
Debugging and error handling: threads are usually more complex in debugging and error handling, because the interaction and concurrent execution between multiple threads can lead to hard-to-debug problems. Coroutines are relatively simpler in debugging and error handling, because their execution flow is explicitly controlled by the programmer.
Overall, threads are suitable for scenarios that require concurrent execution, such as leveraging parallelism on multi-core processors to speed up task execution. Coroutines are suitable for scenarios that require cooperation and coordination, such as state machines, event-driven programming, or cooperative task processing. The choice between threads and coroutines depends on the specific application requirements and programming model.