码迷,mamicode.com
首页 > 其他好文 > 详细

Lua chapter 8 协同程序

时间:2014-05-08 00:21:05      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:lua初学简单笔记

1、协同程序,一个具有多个协同程序的程序在任意时刻,只能运行一个协同程序,
只有正在运行的协同程序被挂起时,它的执行才会暂停。

创建 
co = coroutine.create(匿名函数);   -- 匿名函数就是线程要执行的东东

状态
coroutine.status(co);

唤醒
coroutine.resume(co);

挂起
coroutine.yield();


2、yield-resume 数据交换

function f(a,b)
    coroutine.yield(a*10,b*10);
    return "success";
end;

co = coroutine.create(f);
print (coroutine.resume(co,1,2));   --> true 10,20
print (coroutine.resume(co,1,2));   --> true success


3、消费者,生产者问题  producer and consumer


function receive()
    local status, value = coroutine.resume(producer);
    return value;
end;

function send(value)
    coroutine.yield(value);
end;

--  set random seed 
math.randomseed(os.time());

producer = coroutine.create(
        function()
               while true do
                    value = math.random(1000);
                    send(value);
               end;
         end
);

consumer = coroutine.create(
           function()
                while true do
                      print ("receive ? y or n");
                      if "y" == io.read() then
                            local value = receive();
                            print("receive: " .. value .."\n");
                      else
                            break;
                      end;
                end;
           end
);

coroutine.resume(consumer);


4、Lua的协同程序,在任意时刻只能有一个在执行,通过yield-resume来实现不同协同程序间的切换

function f1()
     for i=1, 100 do
          print("f1", i);
          coroutine.yield();
     end;
end;

function f2()
     for i=1, 100 do
          print("  f2", i);
          coroutine.yield();
     end;
end;

c1 = coroutine.create(f1);
c2 = coroutine.create(f2);

thread ={c1,c2};

function dispatch()
      math.randomseed(os.time());
      while true do
            var = math.random(#thread);       -- 随机数,决定执行哪个协同程序
            local status = coroutine.resume(thread[var]);
            if status==false then       -- 如果一条协同程序执行完,则remove
                 print("thread dead");
                 table.remove(thread,var);
             end;
             if #thread == 0 then       -- 协同程序执行完,退出循环
                 break;
             end;
       end;
end;

dispatch();


Lua chapter 8 协同程序,布布扣,bubuko.com

Lua chapter 8 协同程序

标签:lua初学简单笔记

原文地址:http://blog.csdn.net/core__code/article/details/25219551

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!