Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Coroutine(coroutine)

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

(

)

   

print

(

"Coroutine foo starts executing"

)

   

local

value

=

coroutine.yield

(

"Pause foo's execution"

)

   

print

(

"Coroutine foo resumes execution, the value passed in is: "

..

tostring

(

value

)

)

   

print

(

"Coroutine foo finishes executing"

)

end

-- create a coroutine

local

co

=

coroutine.create

(

foo

)

-- start the coroutine

local

status

,

result

=

coroutine.resume

(

co

)

print

(

result

)

-- output: pause foo's execution

-- resume the coroutine's execution and pass in a value

status

,

result

=

coroutine.resume

(

co

,

42

)

print

(

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

)

       

print

(

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

print

(

coroutine.status

(

co

)

)

 

-- dead

 

print

(

"----------"

)

-- used coroutine.wrap to create a coroutine wrapper, converting the coroutine function into a directly callable function object

co

=

coroutine.wrap

(

   

function

(

i

)

       

print

(

i

)

;

   

end

)

 

co

(

1

)

 

print

(

"----------"

)

-- 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

           

print

(

i

)

           

if

i

==

3

then

               

print

(

coroutine.status

(

co2

)

)

 

--running

               

print

(

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

print

(

coroutine.status

(

co2

)

)

 

-- suspended

print

(

coroutine

.

running

(

)

)

 

print

(

"----------"

)

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

)

   

print

(

"foo function output"

,

a

)

   

return

coroutine.yield

(

2

a

)

-- return the value of 2*a

end

 

co

=

coroutine.create

(

function

(

a

,

b

)

   

print

(

"first coroutine execution output"

,

a

,

b

)

-- co-body 1 10

   

local

r

=

foo

(

a

1

)

     

   

print

(

"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

     

   

print

(

"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

)

       

print

(

"main"

,

coroutine.resume

(

co

,

1

,

10

)

)

-- true, 4

print

(

"--divider----"

)

print

(

"main"

,

coroutine.resume

(

co

,

"r"

)

)

-- true 11 -9

print

(

"---divider---"

)

print

(

"main"

,

coroutine.resume

(

co

,

"x"

,

"y"

)

)

-- true 10 end

print

(

"---divider---"

)

print

(

"main"

,

coroutine.resume

(

co

,

"x"

,

"y"

)

)

-- cannot resume dead coroutine

print

(

"---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:

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

         

print

(

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:

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.