Cooperative Multitasking
Lua coroutines can be used as concurrent tasks. After creating a coroutine task with async_task, the task will not execute immediately. It only starts running when passed to wait_all or wait_any.
Create Coroutine Task 3.0
Creates a coroutine task. The task will not execute until wait_all or wait_any is called.
- Function:
async_taskfrom the lua module - Parameters:
- fun: [function] The function to run
- args: [any] Arguments passed to function
fun, optional
- Returns: [thread] Coroutine task
Compatibility Note
Equivalent to:
task = coroutine.create(function() return fun(args) end)
Example
task = async_task(function(a, b)
print(a + b)
end, 1, 2)
Wait for All Tasks 3.0
Waits for all coroutine tasks to complete and returns each task's return value. If any task throws an error, the error is propagated upward.
- Function:
wait_allfrom the lua module - Parameters:
- tasks: [thread] Coroutine tasks, multiple can be passed
- Returns: [any] Return values of each coroutine task, in the order they were passed
Example
function motion(param)
print(param, 'start running')
movej({j1=0, j2=0, j3=0, j4=0, j5=0, j6=0}, 0, 0, 1, 0)
sync() -- Wait for motion to complete
return "motion complete"
end
function gripper()
wait(1000)
set_claw(0, 100)
return "gripper complete"
end
ret1, ret2 = wait_all(async_task(motion, 'thread 1'), async_task(gripper))
print("motion task return value: ", ret1)
print("gripper task return value: ", ret2)
Wait for Any Task 3.0
Waits for any one coroutine task to complete, returning the first completed task's return value and its index in the parameter list.
- Function:
wait_anyfrom the lua module - Parameters:
- tasks: [thread] Coroutine tasks, multiple can be passed
- Returns:
ret, index.retis the return value of the completed task, ornilif no tasks exist;indexis the position of the completed task in the parameter list (starting from 1), or-1if no tasks exist
Example
local task_timeout = async_task(wait, 1000) -- Create a timeout task
ret, index = wait_any(async_task(motion, 'thread 2'), task_timeout)
if index == 2 then -- task_timeout completed first
print("timeout")
else -- motion completed first
print("motion task return value: ", ret)
end
Query Coroutine Task Status 3.0
Advances coroutine task execution and returns the task status.
- Function:
async_resultfrom the lua module - Parameters:
- task: [thread] Coroutine task
- Returns:
status, result.statusis the task status:"running": running;"finish": completed,resultis the task's return value;"dead": task terminated due to error
Example
task = async_task(function() return "ok" end)
wait_all(task)
status, result = async_result(task)
print(status, result) -- finish ok
