函数:thread.createSubThread 创建子协程

函数名称:创建子协程

函数功能:在协程中创建一个子协程,关闭协程可自动把里面的子协程全关闭

引擎版本:iOS v2.3.9,Android v2.3.4 以上

函数方法

tid = thread.createSubThread(task,back)

参数 类型 必填 说明
task funtion 将该函数加入队列
back table 错误回调,当执行任务时发生错误异常,则会回调这个函数并不再抛出
返回值 类型 说明
tid number 协程 ID,ID 可用于结束或是等待一个任务

函数用例

--子协程会在协程停止后,自动停止
local thread = require('thread')
local thread_id = thread.create(function()
    --创建子协程
    local sub_thread_id_1 = thread.createSubThread(function()
        mSleep(3000)
        --因为 sub thread 1 比 parent thread 运行时间短,所以以下代码会被执行
        toast("sub thread 1 over",3)
    end)
    local sub_thread_id_2 = thread.createSubThread(function()

        --创建子协程的子协程
        local sub_thread_2_sub_thread_1 = thread.createSubThread(function()
            mSleep(1000)
            toast("sub thread 2,sub thread 1 over",3)
        end)

        mSleep(6000)
        --因为 sub thread 2 比 parent thread 运行时间长,所以以下代码实际执行不到
        toast("sub thread 2 over",3)
    end)
    mSleep(4000)
    toast("parent thread over",3)
end)
--等待所有协程结束,只能用于主线程
thread.waitAllThreadExit()
Copyright 北京帮你玩科技有限公司 2023 all right reserved,powered by Gitbook该文章修订时间: 2024-03-06 17:50:18

results matching ""

    No results matching ""