tolua#的Examples-07_LuaThread

关键代码:

    string script =
        @"
            function CoFunc(len)
                print('Coroutine started')                
                local i = 0
                for i = 0, len, 1 do                    
                    local flag = coroutine.yield(fib(i))                    
                    if not flag then
                        break
                    end                                      
                end
                print('Coroutine ended')
            end

            function Test()                
                local co = coroutine.create(CoFunc)                                
                return co
            end            
        ";

    void Start ()
    {
        state = new LuaState();
        state.Start();
        state.DoString(script);

        LuaFunction func = state.GetFunction("Test");
        func.BeginPCall();
        func.PCall();
        thread = func.CheckLuaThread();
        func.EndPCall();
        func.Dispose();
        func = null;

        thread.Resume(10);
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 120, 40), "Resume Thead"))
        {
            if (thread != null && thread.Resume(true) == (int)LuaThreadStatus.LUA_YIELD)
            {
                object[] objs = thread.GetResult();
                Debugger.Log("lua yield: " + objs[0]);
            }
        }
        else if (GUI.Button(new Rect(10, 60, 120, 40), "Close Thread"))
        {
            if (thread != null)
            {                
                thread.Dispose();
                thread = null;
            }
        }
    }

Lua不支持真正的多线程,而是一种协作式的多线程,彼此之间协作完成,并不是抢占完成任务。因此这个例子演示的是如何创建:thread = func.CheckLuaThread();如何唤醒线程:thread.Resume(true)等等

上一篇: tolua#的Examples-06_LuaCoroutine2
下一篇: tolua#的Examples-08_AccessingArray
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭